xref: /freebsd/sys/netpfil/pf/pf.c (revision 347dd0539f3a75fdf2128dd4620ca99e96f311e9)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001 Daniel Hartmeier
5  * Copyright (c) 2002 - 2008 Henning Brauer
6  * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  *    - Redistributions of source code must retain the above copyright
14  *      notice, this list of conditions and the following disclaimer.
15  *    - Redistributions in binary form must reproduce the above
16  *      copyright notice, this list of conditions and the following
17  *      disclaimer in the documentation and/or other materials provided
18  *      with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  *
33  * Effort sponsored in part by the Defense Advanced Research Projects
34  * Agency (DARPA) and Air Force Research Laboratory, Air Force
35  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
36  *
37  *	$OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
38  */
39 
40 #include <sys/cdefs.h>
41 #include "opt_bpf.h"
42 #include "opt_inet.h"
43 #include "opt_inet6.h"
44 #include "opt_pf.h"
45 #include "opt_sctp.h"
46 
47 #include <sys/param.h>
48 #include <sys/bus.h>
49 #include <sys/endian.h>
50 #include <sys/gsb_crc32.h>
51 #include <sys/hash.h>
52 #include <sys/interrupt.h>
53 #include <sys/kernel.h>
54 #include <sys/kthread.h>
55 #include <sys/limits.h>
56 #include <sys/mbuf.h>
57 #include <sys/md5.h>
58 #include <sys/random.h>
59 #include <sys/refcount.h>
60 #include <sys/sdt.h>
61 #include <sys/socket.h>
62 #include <sys/sysctl.h>
63 #include <sys/taskqueue.h>
64 #include <sys/ucred.h>
65 
66 #include <net/if.h>
67 #include <net/if_var.h>
68 #include <net/if_private.h>
69 #include <net/if_types.h>
70 #include <net/if_vlan_var.h>
71 #include <net/route.h>
72 #include <net/route/nhop.h>
73 #include <net/vnet.h>
74 
75 #include <net/pfil.h>
76 #include <net/pfvar.h>
77 #include <net/if_pflog.h>
78 #include <net/if_pfsync.h>
79 
80 #include <netinet/in_pcb.h>
81 #include <netinet/in_var.h>
82 #include <netinet/in_fib.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_fw.h>
85 #include <netinet/ip_icmp.h>
86 #include <netinet/icmp_var.h>
87 #include <netinet/ip_var.h>
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/udp.h>
94 #include <netinet/udp_var.h>
95 
96 /* dummynet */
97 #include <netinet/ip_dummynet.h>
98 #include <netinet/ip_fw.h>
99 #include <netpfil/ipfw/dn_heap.h>
100 #include <netpfil/ipfw/ip_fw_private.h>
101 #include <netpfil/ipfw/ip_dn_private.h>
102 
103 #ifdef INET6
104 #include <netinet/ip6.h>
105 #include <netinet/icmp6.h>
106 #include <netinet6/nd6.h>
107 #include <netinet6/ip6_var.h>
108 #include <netinet6/in6_pcb.h>
109 #include <netinet6/in6_fib.h>
110 #include <netinet6/scope6_var.h>
111 #endif /* INET6 */
112 
113 #include <netinet/sctp_header.h>
114 #include <netinet/sctp_crc32.h>
115 
116 #include <machine/in_cksum.h>
117 #include <security/mac/mac_framework.h>
118 
119 #define	DPFPRINTF(n, x)	if (V_pf_status.debug >= (n)) printf x
120 
121 SDT_PROVIDER_DEFINE(pf);
122 SDT_PROBE_DEFINE4(pf, ip, test, done, "int", "int", "struct pf_krule *",
123     "struct pf_kstate *");
124 SDT_PROBE_DEFINE5(pf, ip, state, lookup, "struct pfi_kkif *",
125     "struct pf_state_key_cmp *", "int", "struct pf_pdesc *",
126     "struct pf_kstate *");
127 SDT_PROBE_DEFINE2(pf, ip, , bound_iface, "struct pf_kstate *",
128     "struct pfi_kkif *");
129 SDT_PROBE_DEFINE4(pf, ip, route_to, entry, "struct mbuf *",
130     "struct pf_pdesc *", "struct pf_kstate *", "struct ifnet *");
131 SDT_PROBE_DEFINE1(pf, ip, route_to, drop, "int");
132 SDT_PROBE_DEFINE2(pf, ip, route_to, output, "struct ifnet *", "int");
133 SDT_PROBE_DEFINE4(pf, ip6, route_to, entry, "struct mbuf *",
134     "struct pf_pdesc *", "struct pf_kstate *", "struct ifnet *");
135 SDT_PROBE_DEFINE1(pf, ip6, route_to, drop, "int");
136 SDT_PROBE_DEFINE2(pf, ip6, route_to, output, "struct ifnet *", "int");
137 SDT_PROBE_DEFINE4(pf, sctp, multihome, test, "struct pfi_kkif *",
138     "struct pf_krule *", "struct mbuf *", "int");
139 SDT_PROBE_DEFINE2(pf, sctp, multihome, add, "uint32_t",
140     "struct pf_sctp_source *");
141 SDT_PROBE_DEFINE3(pf, sctp, multihome, remove, "uint32_t",
142     "struct pf_kstate *", "struct pf_sctp_source *");
143 
144 SDT_PROBE_DEFINE3(pf, eth, test_rule, entry, "int", "struct ifnet *",
145     "struct mbuf *");
146 SDT_PROBE_DEFINE2(pf, eth, test_rule, test, "int", "struct pf_keth_rule *");
147 SDT_PROBE_DEFINE3(pf, eth, test_rule, mismatch,
148     "int", "struct pf_keth_rule *", "char *");
149 SDT_PROBE_DEFINE2(pf, eth, test_rule, match, "int", "struct pf_keth_rule *");
150 SDT_PROBE_DEFINE2(pf, eth, test_rule, final_match,
151     "int", "struct pf_keth_rule *");
152 SDT_PROBE_DEFINE2(pf, purge, state, rowcount, "int", "size_t");
153 
154 /*
155  * Global variables
156  */
157 
158 /* state tables */
159 VNET_DEFINE(struct pf_altqqueue,	 pf_altqs[4]);
160 VNET_DEFINE(struct pf_kpalist,		 pf_pabuf);
161 VNET_DEFINE(struct pf_altqqueue *,	 pf_altqs_active);
162 VNET_DEFINE(struct pf_altqqueue *,	 pf_altq_ifs_active);
163 VNET_DEFINE(struct pf_altqqueue *,	 pf_altqs_inactive);
164 VNET_DEFINE(struct pf_altqqueue *,	 pf_altq_ifs_inactive);
165 VNET_DEFINE(struct pf_kstatus,		 pf_status);
166 
167 VNET_DEFINE(u_int32_t,			 ticket_altqs_active);
168 VNET_DEFINE(u_int32_t,			 ticket_altqs_inactive);
169 VNET_DEFINE(int,			 altqs_inactive_open);
170 VNET_DEFINE(u_int32_t,			 ticket_pabuf);
171 
172 VNET_DEFINE(MD5_CTX,			 pf_tcp_secret_ctx);
173 #define	V_pf_tcp_secret_ctx		 VNET(pf_tcp_secret_ctx)
174 VNET_DEFINE(u_char,			 pf_tcp_secret[16]);
175 #define	V_pf_tcp_secret			 VNET(pf_tcp_secret)
176 VNET_DEFINE(int,			 pf_tcp_secret_init);
177 #define	V_pf_tcp_secret_init		 VNET(pf_tcp_secret_init)
178 VNET_DEFINE(int,			 pf_tcp_iss_off);
179 #define	V_pf_tcp_iss_off		 VNET(pf_tcp_iss_off)
180 VNET_DECLARE(int,			 pf_vnet_active);
181 #define	V_pf_vnet_active		 VNET(pf_vnet_active)
182 
183 VNET_DEFINE_STATIC(uint32_t, pf_purge_idx);
184 #define V_pf_purge_idx	VNET(pf_purge_idx)
185 
186 #ifdef PF_WANT_32_TO_64_COUNTER
187 VNET_DEFINE_STATIC(uint32_t, pf_counter_periodic_iter);
188 #define	V_pf_counter_periodic_iter	VNET(pf_counter_periodic_iter)
189 
190 VNET_DEFINE(struct allrulelist_head, pf_allrulelist);
191 VNET_DEFINE(size_t, pf_allrulecount);
192 VNET_DEFINE(struct pf_krule *, pf_rulemarker);
193 #endif
194 
195 struct pf_sctp_endpoint;
196 RB_HEAD(pf_sctp_endpoints, pf_sctp_endpoint);
197 struct pf_sctp_source {
198 	sa_family_t			af;
199 	struct pf_addr			addr;
200 	TAILQ_ENTRY(pf_sctp_source)	entry;
201 };
202 TAILQ_HEAD(pf_sctp_sources, pf_sctp_source);
203 struct pf_sctp_endpoint
204 {
205 	uint32_t		 v_tag;
206 	struct pf_sctp_sources	 sources;
207 	RB_ENTRY(pf_sctp_endpoint)	entry;
208 };
209 static int
pf_sctp_endpoint_compare(struct pf_sctp_endpoint * a,struct pf_sctp_endpoint * b)210 pf_sctp_endpoint_compare(struct pf_sctp_endpoint *a, struct pf_sctp_endpoint *b)
211 {
212 	return (a->v_tag - b->v_tag);
213 }
214 RB_PROTOTYPE(pf_sctp_endpoints, pf_sctp_endpoint, entry, pf_sctp_endpoint_compare);
215 RB_GENERATE(pf_sctp_endpoints, pf_sctp_endpoint, entry, pf_sctp_endpoint_compare);
216 VNET_DEFINE_STATIC(struct pf_sctp_endpoints, pf_sctp_endpoints);
217 #define V_pf_sctp_endpoints	VNET(pf_sctp_endpoints)
218 static struct mtx_padalign pf_sctp_endpoints_mtx;
219 MTX_SYSINIT(pf_sctp_endpoints_mtx, &pf_sctp_endpoints_mtx, "SCTP endpoints", MTX_DEF);
220 #define	PF_SCTP_ENDPOINTS_LOCK()	mtx_lock(&pf_sctp_endpoints_mtx)
221 #define	PF_SCTP_ENDPOINTS_UNLOCK()	mtx_unlock(&pf_sctp_endpoints_mtx)
222 
223 /*
224  * Queue for pf_intr() sends.
225  */
226 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
227 struct pf_send_entry {
228 	STAILQ_ENTRY(pf_send_entry)	pfse_next;
229 	struct mbuf			*pfse_m;
230 	enum {
231 		PFSE_IP,
232 		PFSE_IP6,
233 		PFSE_ICMP,
234 		PFSE_ICMP6,
235 	}				pfse_type;
236 	struct {
237 		int		type;
238 		int		code;
239 		int		mtu;
240 	} icmpopts;
241 };
242 
243 STAILQ_HEAD(pf_send_head, pf_send_entry);
244 VNET_DEFINE_STATIC(struct pf_send_head, pf_sendqueue);
245 #define	V_pf_sendqueue	VNET(pf_sendqueue)
246 
247 static struct mtx_padalign pf_sendqueue_mtx;
248 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
249 #define	PF_SENDQ_LOCK()		mtx_lock(&pf_sendqueue_mtx)
250 #define	PF_SENDQ_UNLOCK()	mtx_unlock(&pf_sendqueue_mtx)
251 
252 /*
253  * Queue for pf_overload_task() tasks.
254  */
255 struct pf_overload_entry {
256 	SLIST_ENTRY(pf_overload_entry)	next;
257 	struct pf_addr  		addr;
258 	sa_family_t			af;
259 	uint8_t				dir;
260 	struct pf_krule  		*rule;
261 };
262 
263 SLIST_HEAD(pf_overload_head, pf_overload_entry);
264 VNET_DEFINE_STATIC(struct pf_overload_head, pf_overloadqueue);
265 #define V_pf_overloadqueue	VNET(pf_overloadqueue)
266 VNET_DEFINE_STATIC(struct task, pf_overloadtask);
267 #define	V_pf_overloadtask	VNET(pf_overloadtask)
268 
269 static struct mtx_padalign pf_overloadqueue_mtx;
270 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
271     "pf overload/flush queue", MTX_DEF);
272 #define	PF_OVERLOADQ_LOCK()	mtx_lock(&pf_overloadqueue_mtx)
273 #define	PF_OVERLOADQ_UNLOCK()	mtx_unlock(&pf_overloadqueue_mtx)
274 
275 VNET_DEFINE(struct pf_krulequeue, pf_unlinked_rules);
276 struct mtx_padalign pf_unlnkdrules_mtx;
277 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
278     MTX_DEF);
279 
280 struct sx pf_config_lock;
281 SX_SYSINIT(pf_config_lock, &pf_config_lock, "pf config");
282 
283 struct mtx_padalign pf_table_stats_lock;
284 MTX_SYSINIT(pf_table_stats_lock, &pf_table_stats_lock, "pf table stats",
285     MTX_DEF);
286 
287 VNET_DEFINE_STATIC(uma_zone_t,	pf_sources_z);
288 #define	V_pf_sources_z	VNET(pf_sources_z)
289 uma_zone_t		pf_mtag_z;
290 VNET_DEFINE(uma_zone_t,	 pf_state_z);
291 VNET_DEFINE(uma_zone_t,	 pf_state_key_z);
292 VNET_DEFINE(uma_zone_t,	 pf_udp_mapping_z);
293 
294 VNET_DEFINE(struct unrhdr64, pf_stateid);
295 
296 static void		 pf_src_tree_remove_state(struct pf_kstate *);
297 static void		 pf_init_threshold(struct pf_threshold *, u_int32_t,
298 			    u_int32_t);
299 static void		 pf_add_threshold(struct pf_threshold *);
300 static int		 pf_check_threshold(struct pf_threshold *);
301 
302 static void		 pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
303 			    u_int16_t *, u_int16_t *, struct pf_addr *,
304 			    u_int16_t, u_int8_t, sa_family_t);
305 static int		 pf_modulate_sack(struct pf_pdesc *,
306 			    struct tcphdr *, struct pf_state_peer *);
307 int			 pf_icmp_mapping(struct pf_pdesc *, u_int8_t, int *,
308 			    int *, u_int16_t *, u_int16_t *);
309 static void		 pf_change_icmp(struct pf_addr *, u_int16_t *,
310 			    struct pf_addr *, struct pf_addr *, u_int16_t,
311 			    u_int16_t *, u_int16_t *, u_int16_t *,
312 			    u_int16_t *, u_int8_t, sa_family_t);
313 static void		 pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
314 			    sa_family_t, struct pf_krule *, int);
315 static void		 pf_detach_state(struct pf_kstate *);
316 static int		 pf_state_key_attach(struct pf_state_key *,
317 			    struct pf_state_key *, struct pf_kstate *);
318 static void		 pf_state_key_detach(struct pf_kstate *, int);
319 static int		 pf_state_key_ctor(void *, int, void *, int);
320 static u_int32_t	 pf_tcp_iss(struct pf_pdesc *);
321 static __inline void	 pf_dummynet_flag_remove(struct mbuf *m,
322 			    struct pf_mtag *pf_mtag);
323 static int		 pf_dummynet(struct pf_pdesc *, struct pf_kstate *,
324 			    struct pf_krule *, struct mbuf **);
325 static int		 pf_dummynet_route(struct pf_pdesc *,
326 			    struct pf_kstate *, struct pf_krule *,
327 			    struct ifnet *, struct sockaddr *, struct mbuf **);
328 static int		 pf_test_eth_rule(int, struct pfi_kkif *,
329 			    struct mbuf **);
330 static int		 pf_test_rule(struct pf_krule **, struct pf_kstate **,
331 			    struct pf_pdesc *, struct pf_krule **,
332 			    struct pf_kruleset **, struct inpcb *);
333 static int		 pf_create_state(struct pf_krule *, struct pf_krule *,
334 			    struct pf_krule *, struct pf_pdesc *,
335 			    struct pf_state_key *, struct pf_state_key *,
336 			    u_int16_t, u_int16_t, int *,
337 			    struct pf_kstate **, int, u_int16_t, u_int16_t,
338 			    struct pf_krule_slist *, struct pf_udp_mapping *);
339 static int		 pf_state_key_addr_setup(struct pf_pdesc *,
340 			    struct pf_state_key_cmp *, int);
341 static int		 pf_tcp_track_full(struct pf_kstate **,
342 			    struct pf_pdesc *, u_short *, int *);
343 static int		 pf_tcp_track_sloppy(struct pf_kstate **,
344 			    struct pf_pdesc *, u_short *);
345 static int		 pf_test_state_tcp(struct pf_kstate **,
346 			    struct pf_pdesc *, u_short *);
347 static int		 pf_test_state_udp(struct pf_kstate **,
348 			    struct pf_pdesc *);
349 int			 pf_icmp_state_lookup(struct pf_state_key_cmp *,
350 			    struct pf_pdesc *, struct pf_kstate **,
351 			    int, u_int16_t, u_int16_t,
352 			    int, int *, int, int);
353 static int		 pf_test_state_icmp(struct pf_kstate **,
354 			    struct pf_pdesc *, u_short *);
355 static void		 pf_sctp_multihome_detach_addr(const struct pf_kstate *);
356 static void		 pf_sctp_multihome_delayed(struct pf_pdesc *,
357 			    struct pfi_kkif *, struct pf_kstate *, int);
358 static int		 pf_test_state_sctp(struct pf_kstate **,
359 			    struct pf_pdesc *, u_short *);
360 static int		 pf_test_state_other(struct pf_kstate **,
361 			    struct pf_pdesc *);
362 static u_int16_t	 pf_calc_mss(struct pf_addr *, sa_family_t,
363 				int, u_int16_t);
364 static int		 pf_check_proto_cksum(struct mbuf *, int, int,
365 			    u_int8_t, sa_family_t);
366 static int		 pf_walk_option6(struct mbuf *, int, int, uint32_t *,
367 			    u_short *);
368 static void		 pf_print_state_parts(struct pf_kstate *,
369 			    struct pf_state_key *, struct pf_state_key *);
370 static void		 pf_patch_8(struct mbuf *, u_int16_t *, u_int8_t *, u_int8_t,
371 			    bool, u_int8_t);
372 static struct pf_kstate	*pf_find_state(struct pfi_kkif *,
373 			    const struct pf_state_key_cmp *, u_int);
374 static bool		 pf_src_connlimit(struct pf_kstate *);
375 static int		 pf_match_rcvif(struct mbuf *, struct pf_krule *);
376 static void		 pf_counters_inc(int, struct pf_pdesc *,
377 			    struct pf_kstate *, struct pf_krule *,
378 			    struct pf_krule *);
379 static void		 pf_overload_task(void *v, int pending);
380 static u_short		 pf_insert_src_node(struct pf_ksrc_node **,
381 			    struct pf_srchash **, struct pf_krule *,
382 			    struct pf_addr *, sa_family_t);
383 static u_int		 pf_purge_expired_states(u_int, int);
384 static void		 pf_purge_unlinked_rules(void);
385 static int		 pf_mtag_uminit(void *, int, int);
386 static void		 pf_mtag_free(struct m_tag *);
387 static void		 pf_packet_rework_nat(struct mbuf *, struct pf_pdesc *,
388 			    int, struct pf_state_key *);
389 #ifdef INET
390 static void		 pf_route(struct mbuf **, struct pf_krule *,
391 			    struct ifnet *, struct pf_kstate *,
392 			    struct pf_pdesc *, struct inpcb *);
393 #endif /* INET */
394 #ifdef INET6
395 static void		 pf_change_a6(struct pf_addr *, u_int16_t *,
396 			    struct pf_addr *, u_int8_t);
397 static void		 pf_route6(struct mbuf **, struct pf_krule *,
398 			    struct ifnet *, struct pf_kstate *,
399 			    struct pf_pdesc *, struct inpcb *);
400 #endif /* INET6 */
401 static __inline void pf_set_protostate(struct pf_kstate *, int, u_int8_t);
402 
403 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
404 
405 extern int pf_end_threads;
406 extern struct proc *pf_purge_proc;
407 
408 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
409 
410 enum { PF_ICMP_MULTI_NONE, PF_ICMP_MULTI_LINK };
411 
412 #define	PACKET_UNDO_NAT(_m, _pd, _off, _s)		\
413 	do {								\
414 		struct pf_state_key *nk;				\
415 		if ((pd->dir) == PF_OUT)					\
416 			nk = (_s)->key[PF_SK_STACK];			\
417 		else							\
418 			nk = (_s)->key[PF_SK_WIRE];			\
419 		pf_packet_rework_nat(_m, _pd, _off, nk);		\
420 	} while (0)
421 
422 #define	PACKET_LOOPED(pd)	((pd)->pf_mtag &&			\
423 				 (pd)->pf_mtag->flags & PF_MTAG_FLAG_PACKET_LOOPED)
424 
425 #define	STATE_LOOKUP(k, s, pd)						\
426 	do {								\
427 		(s) = pf_find_state((pd->kif), (k), (pd->dir));		\
428 		SDT_PROBE5(pf, ip, state, lookup, pd->kif, k, (pd->dir), pd, (s));	\
429 		if ((s) == NULL)					\
430 			return (PF_DROP);				\
431 		if (PACKET_LOOPED(pd))					\
432 			return (PF_PASS);				\
433 	} while (0)
434 
435 static struct pfi_kkif *
BOUND_IFACE(struct pf_kstate * st,struct pfi_kkif * k)436 BOUND_IFACE(struct pf_kstate *st, struct pfi_kkif *k)
437 {
438 	SDT_PROBE2(pf, ip, , bound_iface, st, k);
439 
440 	/* Floating unless otherwise specified. */
441 	if (! (st->rule->rule_flag & PFRULE_IFBOUND))
442 		return (V_pfi_all);
443 
444 	/*
445 	 * Initially set to all, because we don't know what interface we'll be
446 	 * sending this out when we create the state.
447 	 */
448 	if (st->rule->rt == PF_REPLYTO)
449 		return (V_pfi_all);
450 
451 	/* Don't overrule the interface for states created on incoming packets. */
452 	if (st->direction == PF_IN)
453 		return (k);
454 
455 	/* No route-to, so don't overrule. */
456 	if (st->rt != PF_ROUTETO)
457 		return (k);
458 
459 	/* Bind to the route-to interface. */
460 	return (st->rt_kif);
461 }
462 
463 #define	STATE_INC_COUNTERS(s)						\
464 	do {								\
465 		struct pf_krule_item *mrm;				\
466 		counter_u64_add(s->rule->states_cur, 1);		\
467 		counter_u64_add(s->rule->states_tot, 1);		\
468 		if (s->anchor != NULL) {				\
469 			counter_u64_add(s->anchor->states_cur, 1);	\
470 			counter_u64_add(s->anchor->states_tot, 1);	\
471 		}							\
472 		if (s->nat_rule != NULL) {				\
473 			counter_u64_add(s->nat_rule->states_cur, 1);\
474 			counter_u64_add(s->nat_rule->states_tot, 1);\
475 		}							\
476 		SLIST_FOREACH(mrm, &s->match_rules, entry) {		\
477 			counter_u64_add(mrm->r->states_cur, 1);		\
478 			counter_u64_add(mrm->r->states_tot, 1);		\
479 		}							\
480 	} while (0)
481 
482 #define	STATE_DEC_COUNTERS(s)						\
483 	do {								\
484 		struct pf_krule_item *mrm;				\
485 		if (s->nat_rule != NULL)				\
486 			counter_u64_add(s->nat_rule->states_cur, -1);\
487 		if (s->anchor != NULL)				\
488 			counter_u64_add(s->anchor->states_cur, -1);	\
489 		counter_u64_add(s->rule->states_cur, -1);		\
490 		SLIST_FOREACH(mrm, &s->match_rules, entry)		\
491 			counter_u64_add(mrm->r->states_cur, -1);	\
492 	} while (0)
493 
494 MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
495 MALLOC_DEFINE(M_PF_RULE_ITEM, "pf_krule_item", "pf(4) rule items");
496 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
497 VNET_DEFINE(struct pf_idhash *, pf_idhash);
498 VNET_DEFINE(struct pf_srchash *, pf_srchash);
499 VNET_DEFINE(struct pf_udpendpointhash *, pf_udpendpointhash);
500 VNET_DEFINE(struct pf_udpendpointmapping *, pf_udpendpointmapping);
501 
502 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
503     "pf(4)");
504 
505 VNET_DEFINE(u_long, pf_hashmask);
506 VNET_DEFINE(u_long, pf_srchashmask);
507 VNET_DEFINE(u_long, pf_udpendpointhashmask);
508 VNET_DEFINE_STATIC(u_long, pf_hashsize);
509 #define V_pf_hashsize	VNET(pf_hashsize)
510 VNET_DEFINE_STATIC(u_long, pf_srchashsize);
511 #define V_pf_srchashsize	VNET(pf_srchashsize)
512 VNET_DEFINE_STATIC(u_long, pf_udpendpointhashsize);
513 #define V_pf_udpendpointhashsize	VNET(pf_udpendpointhashsize)
514 u_long	pf_ioctl_maxcount = 65535;
515 
516 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_VNET | CTLFLAG_RDTUN,
517     &VNET_NAME(pf_hashsize), 0, "Size of pf(4) states hashtable");
518 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_VNET | CTLFLAG_RDTUN,
519     &VNET_NAME(pf_srchashsize), 0, "Size of pf(4) source nodes hashtable");
520 SYSCTL_ULONG(_net_pf, OID_AUTO, udpendpoint_hashsize, CTLFLAG_VNET | CTLFLAG_RDTUN,
521     &VNET_NAME(pf_udpendpointhashsize), 0, "Size of pf(4) endpoint hashtable");
522 SYSCTL_ULONG(_net_pf, OID_AUTO, request_maxcount, CTLFLAG_RWTUN,
523     &pf_ioctl_maxcount, 0, "Maximum number of tables, addresses, ... in a single ioctl() call");
524 
525 VNET_DEFINE(void *, pf_swi_cookie);
526 VNET_DEFINE(struct intr_event *, pf_swi_ie);
527 
528 VNET_DEFINE(uint32_t, pf_hashseed);
529 #define	V_pf_hashseed	VNET(pf_hashseed)
530 
531 static void
pf_sctp_checksum(struct mbuf * m,int off)532 pf_sctp_checksum(struct mbuf *m, int off)
533 {
534 	uint32_t sum = 0;
535 
536 	/* Zero out the checksum, to enable recalculation. */
537 	m_copyback(m, off + offsetof(struct sctphdr, checksum),
538 	    sizeof(sum), (caddr_t)&sum);
539 
540 	sum = sctp_calculate_cksum(m, off);
541 
542 	m_copyback(m, off + offsetof(struct sctphdr, checksum),
543 	    sizeof(sum), (caddr_t)&sum);
544 }
545 
546 int
pf_addr_cmp(struct pf_addr * a,struct pf_addr * b,sa_family_t af)547 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
548 {
549 
550 	switch (af) {
551 #ifdef INET
552 	case AF_INET:
553 		if (a->addr32[0] > b->addr32[0])
554 			return (1);
555 		if (a->addr32[0] < b->addr32[0])
556 			return (-1);
557 		break;
558 #endif /* INET */
559 #ifdef INET6
560 	case AF_INET6:
561 		if (a->addr32[3] > b->addr32[3])
562 			return (1);
563 		if (a->addr32[3] < b->addr32[3])
564 			return (-1);
565 		if (a->addr32[2] > b->addr32[2])
566 			return (1);
567 		if (a->addr32[2] < b->addr32[2])
568 			return (-1);
569 		if (a->addr32[1] > b->addr32[1])
570 			return (1);
571 		if (a->addr32[1] < b->addr32[1])
572 			return (-1);
573 		if (a->addr32[0] > b->addr32[0])
574 			return (1);
575 		if (a->addr32[0] < b->addr32[0])
576 			return (-1);
577 		break;
578 #endif /* INET6 */
579 	}
580 	return (0);
581 }
582 
583 static bool
pf_is_loopback(sa_family_t af,struct pf_addr * addr)584 pf_is_loopback(sa_family_t af, struct pf_addr *addr)
585 {
586 	switch (af) {
587 #ifdef INET
588 	case AF_INET:
589 		return IN_LOOPBACK(ntohl(addr->v4.s_addr));
590 #endif
591 	case AF_INET6:
592 		return IN6_IS_ADDR_LOOPBACK(&addr->v6);
593 	default:
594 		panic("Unknown af %d", af);
595 	}
596 }
597 
598 static void
pf_packet_rework_nat(struct mbuf * m,struct pf_pdesc * pd,int off,struct pf_state_key * nk)599 pf_packet_rework_nat(struct mbuf *m, struct pf_pdesc *pd, int off,
600 	struct pf_state_key *nk)
601 {
602 
603 	switch (pd->proto) {
604 	case IPPROTO_TCP: {
605 		struct tcphdr *th = &pd->hdr.tcp;
606 
607 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af))
608 			pf_change_ap(m, pd->src, &th->th_sport, pd->ip_sum,
609 			    &th->th_sum, &nk->addr[pd->sidx],
610 			    nk->port[pd->sidx], 0, pd->af);
611 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af))
612 			pf_change_ap(m, pd->dst, &th->th_dport, pd->ip_sum,
613 			    &th->th_sum, &nk->addr[pd->didx],
614 			    nk->port[pd->didx], 0, pd->af);
615 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
616 		break;
617 	}
618 	case IPPROTO_UDP: {
619 		struct udphdr *uh = &pd->hdr.udp;
620 
621 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af))
622 			pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
623 			    &uh->uh_sum, &nk->addr[pd->sidx],
624 			    nk->port[pd->sidx], 1, pd->af);
625 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af))
626 			pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
627 			    &uh->uh_sum, &nk->addr[pd->didx],
628 			    nk->port[pd->didx], 1, pd->af);
629 		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
630 		break;
631 	}
632 	case IPPROTO_SCTP: {
633 		struct sctphdr *sh = &pd->hdr.sctp;
634 		uint16_t checksum = 0;
635 
636 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af)) {
637 			pf_change_ap(m, pd->src, &sh->src_port, pd->ip_sum,
638 			    &checksum, &nk->addr[pd->sidx],
639 			    nk->port[pd->sidx], 1, pd->af);
640 		}
641 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af)) {
642 			pf_change_ap(m, pd->dst, &sh->dest_port, pd->ip_sum,
643 			    &checksum, &nk->addr[pd->didx],
644 			    nk->port[pd->didx], 1, pd->af);
645 		}
646 
647 		break;
648 	}
649 	case IPPROTO_ICMP: {
650 		struct icmp *ih = &pd->hdr.icmp;
651 
652 		if (nk->port[pd->sidx] != ih->icmp_id) {
653 			pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
654 			    ih->icmp_cksum, ih->icmp_id,
655 			    nk->port[pd->sidx], 0);
656 			ih->icmp_id = nk->port[pd->sidx];
657 			pd->sport = &ih->icmp_id;
658 
659 			m_copyback(m, off, ICMP_MINLEN, (caddr_t)ih);
660 		}
661 		/* FALLTHROUGH */
662 	}
663 	default:
664 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af)) {
665 			switch (pd->af) {
666 			case AF_INET:
667 				pf_change_a(&pd->src->v4.s_addr,
668 				    pd->ip_sum, nk->addr[pd->sidx].v4.s_addr,
669 				    0);
670 				break;
671 			case AF_INET6:
672 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
673 				break;
674 			}
675 		}
676 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af)) {
677 			switch (pd->af) {
678 			case AF_INET:
679 				pf_change_a(&pd->dst->v4.s_addr,
680 				    pd->ip_sum, nk->addr[pd->didx].v4.s_addr,
681 				    0);
682 				break;
683 			case AF_INET6:
684 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
685 				break;
686 			}
687 		}
688 		break;
689 	}
690 }
691 
692 static __inline uint32_t
pf_hashkey(const struct pf_state_key * sk)693 pf_hashkey(const struct pf_state_key *sk)
694 {
695 	uint32_t h;
696 
697 	h = murmur3_32_hash32((const uint32_t *)sk,
698 	    sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
699 	    V_pf_hashseed);
700 
701 	return (h & V_pf_hashmask);
702 }
703 
704 __inline uint32_t
pf_hashsrc(struct pf_addr * addr,sa_family_t af)705 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
706 {
707 	uint32_t h;
708 
709 	switch (af) {
710 	case AF_INET:
711 		h = murmur3_32_hash32((uint32_t *)&addr->v4,
712 		    sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
713 		break;
714 	case AF_INET6:
715 		h = murmur3_32_hash32((uint32_t *)&addr->v6,
716 		    sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
717 		break;
718 	}
719 
720 	return (h & V_pf_srchashmask);
721 }
722 
723 static inline uint32_t
pf_hashudpendpoint(struct pf_udp_endpoint * endpoint)724 pf_hashudpendpoint(struct pf_udp_endpoint *endpoint)
725 {
726 	uint32_t h;
727 
728 	h = murmur3_32_hash32((uint32_t *)endpoint,
729 	    sizeof(struct pf_udp_endpoint_cmp)/sizeof(uint32_t),
730 	    V_pf_hashseed);
731 	return (h & V_pf_udpendpointhashmask);
732 }
733 
734 #ifdef ALTQ
735 static int
pf_state_hash(struct pf_kstate * s)736 pf_state_hash(struct pf_kstate *s)
737 {
738 	u_int32_t hv = (intptr_t)s / sizeof(*s);
739 
740 	hv ^= crc32(&s->src, sizeof(s->src));
741 	hv ^= crc32(&s->dst, sizeof(s->dst));
742 	if (hv == 0)
743 		hv = 1;
744 	return (hv);
745 }
746 #endif
747 
748 static __inline void
pf_set_protostate(struct pf_kstate * s,int which,u_int8_t newstate)749 pf_set_protostate(struct pf_kstate *s, int which, u_int8_t newstate)
750 {
751 	if (which == PF_PEER_DST || which == PF_PEER_BOTH)
752 		s->dst.state = newstate;
753 	if (which == PF_PEER_DST)
754 		return;
755 	if (s->src.state == newstate)
756 		return;
757 	if (s->creatorid == V_pf_status.hostid &&
758 	    s->key[PF_SK_STACK] != NULL &&
759 	    s->key[PF_SK_STACK]->proto == IPPROTO_TCP &&
760 	    !(TCPS_HAVEESTABLISHED(s->src.state) ||
761 	    s->src.state == TCPS_CLOSED) &&
762 	    (TCPS_HAVEESTABLISHED(newstate) || newstate == TCPS_CLOSED))
763 		atomic_add_32(&V_pf_status.states_halfopen, -1);
764 
765 	s->src.state = newstate;
766 }
767 
768 #ifdef INET6
769 void
pf_addrcpy(struct pf_addr * dst,struct pf_addr * src,sa_family_t af)770 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
771 {
772 	switch (af) {
773 #ifdef INET
774 	case AF_INET:
775 		memcpy(&dst->v4, &src->v4, sizeof(dst->v4));
776 		break;
777 #endif /* INET */
778 	case AF_INET6:
779 		memcpy(&dst->v6, &src->v6, sizeof(dst->v6));
780 		break;
781 	}
782 }
783 #endif /* INET6 */
784 
785 static void
pf_init_threshold(struct pf_threshold * threshold,u_int32_t limit,u_int32_t seconds)786 pf_init_threshold(struct pf_threshold *threshold,
787     u_int32_t limit, u_int32_t seconds)
788 {
789 	threshold->limit = limit * PF_THRESHOLD_MULT;
790 	threshold->seconds = seconds;
791 	threshold->count = 0;
792 	threshold->last = time_uptime;
793 }
794 
795 static void
pf_add_threshold(struct pf_threshold * threshold)796 pf_add_threshold(struct pf_threshold *threshold)
797 {
798 	u_int32_t t = time_uptime, diff = t - threshold->last;
799 
800 	if (diff >= threshold->seconds)
801 		threshold->count = 0;
802 	else
803 		threshold->count -= threshold->count * diff /
804 		    threshold->seconds;
805 	threshold->count += PF_THRESHOLD_MULT;
806 	threshold->last = t;
807 }
808 
809 static int
pf_check_threshold(struct pf_threshold * threshold)810 pf_check_threshold(struct pf_threshold *threshold)
811 {
812 	return (threshold->count > threshold->limit);
813 }
814 
815 static bool
pf_src_connlimit(struct pf_kstate * state)816 pf_src_connlimit(struct pf_kstate *state)
817 {
818 	struct pf_overload_entry *pfoe;
819 	bool limited = false;
820 
821 	PF_STATE_LOCK_ASSERT(state);
822 	PF_SRC_NODE_LOCK(state->src_node);
823 
824 	state->src_node->conn++;
825 	state->src.tcp_est = 1;
826 	pf_add_threshold(&state->src_node->conn_rate);
827 
828 	if (state->rule->max_src_conn &&
829 	    state->rule->max_src_conn <
830 	    state->src_node->conn) {
831 		counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
832 		limited = true;
833 	}
834 
835 	if (state->rule->max_src_conn_rate.limit &&
836 	    pf_check_threshold(&state->src_node->conn_rate)) {
837 		counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
838 		limited = true;
839 	}
840 
841 	if (!limited)
842 		goto done;
843 
844 	/* Kill this state. */
845 	state->timeout = PFTM_PURGE;
846 	pf_set_protostate(state, PF_PEER_BOTH, TCPS_CLOSED);
847 
848 	if (state->rule->overload_tbl == NULL)
849 		goto done;
850 
851 	/* Schedule overloading and flushing task. */
852 	pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
853 	if (pfoe == NULL)
854 		goto done;  /* too bad :( */
855 
856 	bcopy(&state->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
857 	pfoe->af = state->key[PF_SK_WIRE]->af;
858 	pfoe->rule = state->rule;
859 	pfoe->dir = state->direction;
860 	PF_OVERLOADQ_LOCK();
861 	SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
862 	PF_OVERLOADQ_UNLOCK();
863 	taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
864 
865 done:
866 	PF_SRC_NODE_UNLOCK(state->src_node);
867 	return (limited);
868 }
869 
870 static void
pf_overload_task(void * v,int pending)871 pf_overload_task(void *v, int pending)
872 {
873 	struct pf_overload_head queue;
874 	struct pfr_addr p;
875 	struct pf_overload_entry *pfoe, *pfoe1;
876 	uint32_t killed = 0;
877 
878 	CURVNET_SET((struct vnet *)v);
879 
880 	PF_OVERLOADQ_LOCK();
881 	queue = V_pf_overloadqueue;
882 	SLIST_INIT(&V_pf_overloadqueue);
883 	PF_OVERLOADQ_UNLOCK();
884 
885 	bzero(&p, sizeof(p));
886 	SLIST_FOREACH(pfoe, &queue, next) {
887 		counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
888 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
889 			printf("%s: blocking address ", __func__);
890 			pf_print_host(&pfoe->addr, 0, pfoe->af);
891 			printf("\n");
892 		}
893 
894 		p.pfra_af = pfoe->af;
895 		switch (pfoe->af) {
896 #ifdef INET
897 		case AF_INET:
898 			p.pfra_net = 32;
899 			p.pfra_ip4addr = pfoe->addr.v4;
900 			break;
901 #endif
902 #ifdef INET6
903 		case AF_INET6:
904 			p.pfra_net = 128;
905 			p.pfra_ip6addr = pfoe->addr.v6;
906 			break;
907 #endif
908 		}
909 
910 		PF_RULES_WLOCK();
911 		pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
912 		PF_RULES_WUNLOCK();
913 	}
914 
915 	/*
916 	 * Remove those entries, that don't need flushing.
917 	 */
918 	SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
919 		if (pfoe->rule->flush == 0) {
920 			SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
921 			free(pfoe, M_PFTEMP);
922 		} else
923 			counter_u64_add(
924 			    V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
925 
926 	/* If nothing to flush, return. */
927 	if (SLIST_EMPTY(&queue)) {
928 		CURVNET_RESTORE();
929 		return;
930 	}
931 
932 	for (int i = 0; i <= V_pf_hashmask; i++) {
933 		struct pf_idhash *ih = &V_pf_idhash[i];
934 		struct pf_state_key *sk;
935 		struct pf_kstate *s;
936 
937 		PF_HASHROW_LOCK(ih);
938 		LIST_FOREACH(s, &ih->states, entry) {
939 		    sk = s->key[PF_SK_WIRE];
940 		    SLIST_FOREACH(pfoe, &queue, next)
941 			if (sk->af == pfoe->af &&
942 			    ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
943 			    pfoe->rule == s->rule) &&
944 			    ((pfoe->dir == PF_OUT &&
945 			    PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
946 			    (pfoe->dir == PF_IN &&
947 			    PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
948 				s->timeout = PFTM_PURGE;
949 				pf_set_protostate(s, PF_PEER_BOTH, TCPS_CLOSED);
950 				killed++;
951 			}
952 		}
953 		PF_HASHROW_UNLOCK(ih);
954 	}
955 	SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
956 		free(pfoe, M_PFTEMP);
957 	if (V_pf_status.debug >= PF_DEBUG_MISC)
958 		printf("%s: %u states killed", __func__, killed);
959 
960 	CURVNET_RESTORE();
961 }
962 
963 /*
964  * On node found always returns locked. On not found its configurable.
965  */
966 struct pf_ksrc_node *
pf_find_src_node(struct pf_addr * src,struct pf_krule * rule,sa_family_t af,struct pf_srchash ** sh,bool returnlocked)967 pf_find_src_node(struct pf_addr *src, struct pf_krule *rule, sa_family_t af,
968 	struct pf_srchash **sh, bool returnlocked)
969 {
970 	struct pf_ksrc_node *n;
971 
972 	counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
973 
974 	*sh = &V_pf_srchash[pf_hashsrc(src, af)];
975 	PF_HASHROW_LOCK(*sh);
976 	LIST_FOREACH(n, &(*sh)->nodes, entry)
977 		if (n->rule == rule && n->af == af &&
978 		    ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
979 		    (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
980 			break;
981 
982 	if (n == NULL && !returnlocked)
983 		PF_HASHROW_UNLOCK(*sh);
984 
985 	return (n);
986 }
987 
988 bool
pf_src_node_exists(struct pf_ksrc_node ** sn,struct pf_srchash * sh)989 pf_src_node_exists(struct pf_ksrc_node **sn, struct pf_srchash *sh)
990 {
991 	struct pf_ksrc_node	*cur;
992 
993 	if ((*sn) == NULL)
994 		return (false);
995 
996 	KASSERT(sh != NULL, ("%s: sh is NULL", __func__));
997 
998 	counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
999 	PF_HASHROW_LOCK(sh);
1000 	LIST_FOREACH(cur, &(sh->nodes), entry) {
1001 		if (cur == (*sn) &&
1002 		    cur->expire != 1) /* Ignore nodes being killed */
1003 			return (true);
1004 	}
1005 	PF_HASHROW_UNLOCK(sh);
1006 	(*sn) = NULL;
1007 	return (false);
1008 }
1009 
1010 static void
pf_free_src_node(struct pf_ksrc_node * sn)1011 pf_free_src_node(struct pf_ksrc_node *sn)
1012 {
1013 
1014 	for (int i = 0; i < 2; i++) {
1015 		counter_u64_free(sn->bytes[i]);
1016 		counter_u64_free(sn->packets[i]);
1017 	}
1018 	uma_zfree(V_pf_sources_z, sn);
1019 }
1020 
1021 static u_short
pf_insert_src_node(struct pf_ksrc_node ** sn,struct pf_srchash ** sh,struct pf_krule * rule,struct pf_addr * src,sa_family_t af)1022 pf_insert_src_node(struct pf_ksrc_node **sn, struct pf_srchash **sh,
1023     struct pf_krule *rule, struct pf_addr *src, sa_family_t af)
1024 {
1025 	u_short			 reason = 0;
1026 
1027 	KASSERT((rule->rule_flag & PFRULE_SRCTRACK ||
1028 	    rule->rpool.opts & PF_POOL_STICKYADDR),
1029 	    ("%s for non-tracking rule %p", __func__, rule));
1030 
1031 	/*
1032 	 * Request the sh to always be locked, as we might insert a new sn.
1033 	 */
1034 	if (*sn == NULL)
1035 		*sn = pf_find_src_node(src, rule, af, sh, true);
1036 
1037 	if (*sn == NULL) {
1038 		PF_HASHROW_ASSERT(*sh);
1039 
1040 		if (rule->max_src_nodes &&
1041 		    counter_u64_fetch(rule->src_nodes) >= rule->max_src_nodes) {
1042 			counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES], 1);
1043 			reason = PFRES_SRCLIMIT;
1044 			goto done;
1045 		}
1046 
1047 		(*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
1048 		if ((*sn) == NULL) {
1049 			reason = PFRES_MEMORY;
1050 			goto done;
1051 		}
1052 
1053 		for (int i = 0; i < 2; i++) {
1054 			(*sn)->bytes[i] = counter_u64_alloc(M_NOWAIT);
1055 			(*sn)->packets[i] = counter_u64_alloc(M_NOWAIT);
1056 
1057 			if ((*sn)->bytes[i] == NULL || (*sn)->packets[i] == NULL) {
1058 				pf_free_src_node(*sn);
1059 				reason = PFRES_MEMORY;
1060 				goto done;
1061 			}
1062 		}
1063 
1064 		pf_init_threshold(&(*sn)->conn_rate,
1065 		    rule->max_src_conn_rate.limit,
1066 		    rule->max_src_conn_rate.seconds);
1067 
1068 		MPASS((*sn)->lock == NULL);
1069 		(*sn)->lock = &(*sh)->lock;
1070 
1071 		(*sn)->af = af;
1072 		(*sn)->rule = rule;
1073 		PF_ACPY(&(*sn)->addr, src, af);
1074 		LIST_INSERT_HEAD(&(*sh)->nodes, *sn, entry);
1075 		(*sn)->creation = time_uptime;
1076 		(*sn)->ruletype = rule->action;
1077 		if ((*sn)->rule != NULL)
1078 			counter_u64_add((*sn)->rule->src_nodes, 1);
1079 		counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
1080 	} else {
1081 		if (rule->max_src_states &&
1082 		    (*sn)->states >= rule->max_src_states) {
1083 			counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
1084 			    1);
1085 			reason = PFRES_SRCLIMIT;
1086 			goto done;
1087 		}
1088 	}
1089 done:
1090 	if (reason == 0)
1091 		(*sn)->states++;
1092 	else
1093 		(*sn) = NULL;
1094 
1095 	PF_HASHROW_UNLOCK(*sh);
1096 	return (reason);
1097 }
1098 
1099 void
pf_unlink_src_node(struct pf_ksrc_node * src)1100 pf_unlink_src_node(struct pf_ksrc_node *src)
1101 {
1102 	PF_SRC_NODE_LOCK_ASSERT(src);
1103 
1104 	LIST_REMOVE(src, entry);
1105 	if (src->rule)
1106 		counter_u64_add(src->rule->src_nodes, -1);
1107 }
1108 
1109 u_int
pf_free_src_nodes(struct pf_ksrc_node_list * head)1110 pf_free_src_nodes(struct pf_ksrc_node_list *head)
1111 {
1112 	struct pf_ksrc_node *sn, *tmp;
1113 	u_int count = 0;
1114 
1115 	LIST_FOREACH_SAFE(sn, head, entry, tmp) {
1116 		pf_free_src_node(sn);
1117 		count++;
1118 	}
1119 
1120 	counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
1121 
1122 	return (count);
1123 }
1124 
1125 void
pf_mtag_initialize(void)1126 pf_mtag_initialize(void)
1127 {
1128 
1129 	pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
1130 	    sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
1131 	    UMA_ALIGN_PTR, 0);
1132 }
1133 
1134 /* Per-vnet data storage structures initialization. */
1135 void
pf_initialize(void)1136 pf_initialize(void)
1137 {
1138 	struct pf_keyhash	*kh;
1139 	struct pf_idhash	*ih;
1140 	struct pf_srchash	*sh;
1141 	struct pf_udpendpointhash	*uh;
1142 	u_int i;
1143 
1144 	if (V_pf_hashsize == 0 || !powerof2(V_pf_hashsize))
1145 		V_pf_hashsize = PF_HASHSIZ;
1146 	if (V_pf_srchashsize == 0 || !powerof2(V_pf_srchashsize))
1147 		V_pf_srchashsize = PF_SRCHASHSIZ;
1148 	if (V_pf_udpendpointhashsize == 0 || !powerof2(V_pf_udpendpointhashsize))
1149 		V_pf_udpendpointhashsize = PF_UDPENDHASHSIZ;
1150 
1151 	V_pf_hashseed = arc4random();
1152 
1153 	/* States and state keys storage. */
1154 	V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_kstate),
1155 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1156 	V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
1157 	uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
1158 	uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
1159 
1160 	V_pf_state_key_z = uma_zcreate("pf state keys",
1161 	    sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
1162 	    UMA_ALIGN_PTR, 0);
1163 
1164 	V_pf_keyhash = mallocarray(V_pf_hashsize, sizeof(struct pf_keyhash),
1165 	    M_PFHASH, M_NOWAIT | M_ZERO);
1166 	V_pf_idhash = mallocarray(V_pf_hashsize, sizeof(struct pf_idhash),
1167 	    M_PFHASH, M_NOWAIT | M_ZERO);
1168 	if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
1169 		printf("pf: Unable to allocate memory for "
1170 		    "state_hashsize %lu.\n", V_pf_hashsize);
1171 
1172 		free(V_pf_keyhash, M_PFHASH);
1173 		free(V_pf_idhash, M_PFHASH);
1174 
1175 		V_pf_hashsize = PF_HASHSIZ;
1176 		V_pf_keyhash = mallocarray(V_pf_hashsize,
1177 		    sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
1178 		V_pf_idhash = mallocarray(V_pf_hashsize,
1179 		    sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
1180 	}
1181 
1182 	V_pf_hashmask = V_pf_hashsize - 1;
1183 	for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= V_pf_hashmask;
1184 	    i++, kh++, ih++) {
1185 		mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
1186 		mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
1187 	}
1188 
1189 	/* Source nodes. */
1190 	V_pf_sources_z = uma_zcreate("pf source nodes",
1191 	    sizeof(struct pf_ksrc_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
1192 	    0);
1193 	V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
1194 	uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
1195 	uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
1196 
1197 	V_pf_srchash = mallocarray(V_pf_srchashsize,
1198 	    sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
1199 	if (V_pf_srchash == NULL) {
1200 		printf("pf: Unable to allocate memory for "
1201 		    "source_hashsize %lu.\n", V_pf_srchashsize);
1202 
1203 		V_pf_srchashsize = PF_SRCHASHSIZ;
1204 		V_pf_srchash = mallocarray(V_pf_srchashsize,
1205 		    sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
1206 	}
1207 
1208 	V_pf_srchashmask = V_pf_srchashsize - 1;
1209 	for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++)
1210 		mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
1211 
1212 
1213 	/* UDP endpoint mappings. */
1214 	V_pf_udp_mapping_z = uma_zcreate("pf UDP mappings",
1215 	    sizeof(struct pf_udp_mapping), NULL, NULL, NULL, NULL,
1216 	    UMA_ALIGN_PTR, 0);
1217 	V_pf_udpendpointhash = mallocarray(V_pf_udpendpointhashsize,
1218 	    sizeof(struct pf_udpendpointhash), M_PFHASH, M_NOWAIT | M_ZERO);
1219 	if (V_pf_udpendpointhash == NULL) {
1220 		printf("pf: Unable to allocate memory for "
1221 		    "udpendpoint_hashsize %lu.\n", V_pf_udpendpointhashsize);
1222 
1223 		V_pf_udpendpointhashsize = PF_UDPENDHASHSIZ;
1224 		V_pf_udpendpointhash = mallocarray(V_pf_udpendpointhashsize,
1225 		    sizeof(struct pf_udpendpointhash), M_PFHASH, M_WAITOK | M_ZERO);
1226 	}
1227 
1228 	V_pf_udpendpointhashmask = V_pf_udpendpointhashsize - 1;
1229 	for (i = 0, uh = V_pf_udpendpointhash;
1230 	    i <= V_pf_udpendpointhashmask;
1231 	    i++, uh++) {
1232 		mtx_init(&uh->lock, "pf_udpendpointhash", NULL,
1233 		    MTX_DEF | MTX_DUPOK);
1234 	}
1235 
1236 	/* ALTQ */
1237 	TAILQ_INIT(&V_pf_altqs[0]);
1238 	TAILQ_INIT(&V_pf_altqs[1]);
1239 	TAILQ_INIT(&V_pf_altqs[2]);
1240 	TAILQ_INIT(&V_pf_altqs[3]);
1241 	TAILQ_INIT(&V_pf_pabuf);
1242 	V_pf_altqs_active = &V_pf_altqs[0];
1243 	V_pf_altq_ifs_active = &V_pf_altqs[1];
1244 	V_pf_altqs_inactive = &V_pf_altqs[2];
1245 	V_pf_altq_ifs_inactive = &V_pf_altqs[3];
1246 
1247 	/* Send & overload+flush queues. */
1248 	STAILQ_INIT(&V_pf_sendqueue);
1249 	SLIST_INIT(&V_pf_overloadqueue);
1250 	TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
1251 
1252 	/* Unlinked, but may be referenced rules. */
1253 	TAILQ_INIT(&V_pf_unlinked_rules);
1254 }
1255 
1256 void
pf_mtag_cleanup(void)1257 pf_mtag_cleanup(void)
1258 {
1259 
1260 	uma_zdestroy(pf_mtag_z);
1261 }
1262 
1263 void
pf_cleanup(void)1264 pf_cleanup(void)
1265 {
1266 	struct pf_keyhash	*kh;
1267 	struct pf_idhash	*ih;
1268 	struct pf_srchash	*sh;
1269 	struct pf_udpendpointhash	*uh;
1270 	struct pf_send_entry	*pfse, *next;
1271 	u_int i;
1272 
1273 	for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash;
1274 	    i <= V_pf_hashmask;
1275 	    i++, kh++, ih++) {
1276 		KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
1277 		    __func__));
1278 		KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
1279 		    __func__));
1280 		mtx_destroy(&kh->lock);
1281 		mtx_destroy(&ih->lock);
1282 	}
1283 	free(V_pf_keyhash, M_PFHASH);
1284 	free(V_pf_idhash, M_PFHASH);
1285 
1286 	for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
1287 		KASSERT(LIST_EMPTY(&sh->nodes),
1288 		    ("%s: source node hash not empty", __func__));
1289 		mtx_destroy(&sh->lock);
1290 	}
1291 	free(V_pf_srchash, M_PFHASH);
1292 
1293 	for (i = 0, uh = V_pf_udpendpointhash;
1294 	    i <= V_pf_udpendpointhashmask;
1295 	    i++, uh++) {
1296 		KASSERT(LIST_EMPTY(&uh->endpoints),
1297 		    ("%s: udp endpoint hash not empty", __func__));
1298 		mtx_destroy(&uh->lock);
1299 	}
1300 	free(V_pf_udpendpointhash, M_PFHASH);
1301 
1302 	STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
1303 		m_freem(pfse->pfse_m);
1304 		free(pfse, M_PFTEMP);
1305 	}
1306 	MPASS(RB_EMPTY(&V_pf_sctp_endpoints));
1307 
1308 	uma_zdestroy(V_pf_sources_z);
1309 	uma_zdestroy(V_pf_state_z);
1310 	uma_zdestroy(V_pf_state_key_z);
1311 	uma_zdestroy(V_pf_udp_mapping_z);
1312 }
1313 
1314 static int
pf_mtag_uminit(void * mem,int size,int how)1315 pf_mtag_uminit(void *mem, int size, int how)
1316 {
1317 	struct m_tag *t;
1318 
1319 	t = (struct m_tag *)mem;
1320 	t->m_tag_cookie = MTAG_ABI_COMPAT;
1321 	t->m_tag_id = PACKET_TAG_PF;
1322 	t->m_tag_len = sizeof(struct pf_mtag);
1323 	t->m_tag_free = pf_mtag_free;
1324 
1325 	return (0);
1326 }
1327 
1328 static void
pf_mtag_free(struct m_tag * t)1329 pf_mtag_free(struct m_tag *t)
1330 {
1331 
1332 	uma_zfree(pf_mtag_z, t);
1333 }
1334 
1335 struct pf_mtag *
pf_get_mtag(struct mbuf * m)1336 pf_get_mtag(struct mbuf *m)
1337 {
1338 	struct m_tag *mtag;
1339 
1340 	if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
1341 		return ((struct pf_mtag *)(mtag + 1));
1342 
1343 	mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
1344 	if (mtag == NULL)
1345 		return (NULL);
1346 	bzero(mtag + 1, sizeof(struct pf_mtag));
1347 	m_tag_prepend(m, mtag);
1348 
1349 	return ((struct pf_mtag *)(mtag + 1));
1350 }
1351 
1352 static int
pf_state_key_attach(struct pf_state_key * skw,struct pf_state_key * sks,struct pf_kstate * s)1353 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
1354     struct pf_kstate *s)
1355 {
1356 	struct pf_keyhash	*khs, *khw, *kh;
1357 	struct pf_state_key	*sk, *cur;
1358 	struct pf_kstate	*si, *olds = NULL;
1359 	int idx;
1360 
1361 	NET_EPOCH_ASSERT();
1362 	KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1363 	KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
1364 	KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
1365 
1366 	/*
1367 	 * We need to lock hash slots of both keys. To avoid deadlock
1368 	 * we always lock the slot with lower address first. Unlock order
1369 	 * isn't important.
1370 	 *
1371 	 * We also need to lock ID hash slot before dropping key
1372 	 * locks. On success we return with ID hash slot locked.
1373 	 */
1374 
1375 	if (skw == sks) {
1376 		khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
1377 		PF_HASHROW_LOCK(khs);
1378 	} else {
1379 		khs = &V_pf_keyhash[pf_hashkey(sks)];
1380 		khw = &V_pf_keyhash[pf_hashkey(skw)];
1381 		if (khs == khw) {
1382 			PF_HASHROW_LOCK(khs);
1383 		} else if (khs < khw) {
1384 			PF_HASHROW_LOCK(khs);
1385 			PF_HASHROW_LOCK(khw);
1386 		} else {
1387 			PF_HASHROW_LOCK(khw);
1388 			PF_HASHROW_LOCK(khs);
1389 		}
1390 	}
1391 
1392 #define	KEYS_UNLOCK()	do {			\
1393 	if (khs != khw) {			\
1394 		PF_HASHROW_UNLOCK(khs);		\
1395 		PF_HASHROW_UNLOCK(khw);		\
1396 	} else					\
1397 		PF_HASHROW_UNLOCK(khs);		\
1398 } while (0)
1399 
1400 	/*
1401 	 * First run: start with wire key.
1402 	 */
1403 	sk = skw;
1404 	kh = khw;
1405 	idx = PF_SK_WIRE;
1406 
1407 	MPASS(s->lock == NULL);
1408 	s->lock = &V_pf_idhash[PF_IDHASH(s)].lock;
1409 
1410 keyattach:
1411 	LIST_FOREACH(cur, &kh->keys, entry)
1412 		if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1413 			break;
1414 
1415 	if (cur != NULL) {
1416 		/* Key exists. Check for same kif, if none, add to key. */
1417 		TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1418 			struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1419 
1420 			PF_HASHROW_LOCK(ih);
1421 			if (si->kif == s->kif &&
1422 			    si->direction == s->direction) {
1423 				if (sk->proto == IPPROTO_TCP &&
1424 				    si->src.state >= TCPS_FIN_WAIT_2 &&
1425 				    si->dst.state >= TCPS_FIN_WAIT_2) {
1426 					/*
1427 					 * New state matches an old >FIN_WAIT_2
1428 					 * state. We can't drop key hash locks,
1429 					 * thus we can't unlink it properly.
1430 					 *
1431 					 * As a workaround we drop it into
1432 					 * TCPS_CLOSED state, schedule purge
1433 					 * ASAP and push it into the very end
1434 					 * of the slot TAILQ, so that it won't
1435 					 * conflict with our new state.
1436 					 */
1437 					pf_set_protostate(si, PF_PEER_BOTH,
1438 					    TCPS_CLOSED);
1439 					si->timeout = PFTM_PURGE;
1440 					olds = si;
1441 				} else {
1442 					if (V_pf_status.debug >= PF_DEBUG_MISC) {
1443 						printf("pf: %s key attach "
1444 						    "failed on %s: ",
1445 						    (idx == PF_SK_WIRE) ?
1446 						    "wire" : "stack",
1447 						    s->kif->pfik_name);
1448 						pf_print_state_parts(s,
1449 						    (idx == PF_SK_WIRE) ?
1450 						    sk : NULL,
1451 						    (idx == PF_SK_STACK) ?
1452 						    sk : NULL);
1453 						printf(", existing: ");
1454 						pf_print_state_parts(si,
1455 						    (idx == PF_SK_WIRE) ?
1456 						    sk : NULL,
1457 						    (idx == PF_SK_STACK) ?
1458 						    sk : NULL);
1459 						printf("\n");
1460 					}
1461 					s->timeout = PFTM_UNLINKED;
1462 					PF_HASHROW_UNLOCK(ih);
1463 					KEYS_UNLOCK();
1464 					uma_zfree(V_pf_state_key_z, skw);
1465 					if (skw != sks)
1466 						uma_zfree(V_pf_state_key_z, sks);
1467 					if (idx == PF_SK_STACK)
1468 						pf_detach_state(s);
1469 					return (EEXIST); /* collision! */
1470 				}
1471 			}
1472 			PF_HASHROW_UNLOCK(ih);
1473 		}
1474 		uma_zfree(V_pf_state_key_z, sk);
1475 		s->key[idx] = cur;
1476 	} else {
1477 		LIST_INSERT_HEAD(&kh->keys, sk, entry);
1478 		s->key[idx] = sk;
1479 	}
1480 
1481 stateattach:
1482 	/* List is sorted, if-bound states before floating. */
1483 	if (s->kif == V_pfi_all)
1484 		TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1485 	else
1486 		TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1487 
1488 	if (olds) {
1489 		TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1490 		TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1491 		    key_list[idx]);
1492 		olds = NULL;
1493 	}
1494 
1495 	/*
1496 	 * Attach done. See how should we (or should not?)
1497 	 * attach a second key.
1498 	 */
1499 	if (sks == skw) {
1500 		s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1501 		idx = PF_SK_STACK;
1502 		sks = NULL;
1503 		goto stateattach;
1504 	} else if (sks != NULL) {
1505 		/*
1506 		 * Continue attaching with stack key.
1507 		 */
1508 		sk = sks;
1509 		kh = khs;
1510 		idx = PF_SK_STACK;
1511 		sks = NULL;
1512 		goto keyattach;
1513 	}
1514 
1515 	PF_STATE_LOCK(s);
1516 	KEYS_UNLOCK();
1517 
1518 	KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1519 	    ("%s failure", __func__));
1520 
1521 	return (0);
1522 #undef	KEYS_UNLOCK
1523 }
1524 
1525 static void
pf_detach_state(struct pf_kstate * s)1526 pf_detach_state(struct pf_kstate *s)
1527 {
1528 	struct pf_state_key *sks = s->key[PF_SK_STACK];
1529 	struct pf_keyhash *kh;
1530 
1531 	NET_EPOCH_ASSERT();
1532 	MPASS(s->timeout >= PFTM_MAX);
1533 
1534 	pf_sctp_multihome_detach_addr(s);
1535 
1536 	if ((s->state_flags & PFSTATE_PFLOW) && V_pflow_export_state_ptr)
1537 		V_pflow_export_state_ptr(s);
1538 
1539 	if (sks != NULL) {
1540 		kh = &V_pf_keyhash[pf_hashkey(sks)];
1541 		PF_HASHROW_LOCK(kh);
1542 		if (s->key[PF_SK_STACK] != NULL)
1543 			pf_state_key_detach(s, PF_SK_STACK);
1544 		/*
1545 		 * If both point to same key, then we are done.
1546 		 */
1547 		if (sks == s->key[PF_SK_WIRE]) {
1548 			pf_state_key_detach(s, PF_SK_WIRE);
1549 			PF_HASHROW_UNLOCK(kh);
1550 			return;
1551 		}
1552 		PF_HASHROW_UNLOCK(kh);
1553 	}
1554 
1555 	if (s->key[PF_SK_WIRE] != NULL) {
1556 		kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1557 		PF_HASHROW_LOCK(kh);
1558 		if (s->key[PF_SK_WIRE] != NULL)
1559 			pf_state_key_detach(s, PF_SK_WIRE);
1560 		PF_HASHROW_UNLOCK(kh);
1561 	}
1562 }
1563 
1564 static void
pf_state_key_detach(struct pf_kstate * s,int idx)1565 pf_state_key_detach(struct pf_kstate *s, int idx)
1566 {
1567 	struct pf_state_key *sk = s->key[idx];
1568 #ifdef INVARIANTS
1569 	struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1570 
1571 	PF_HASHROW_ASSERT(kh);
1572 #endif
1573 	TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1574 	s->key[idx] = NULL;
1575 
1576 	if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1577 		LIST_REMOVE(sk, entry);
1578 		uma_zfree(V_pf_state_key_z, sk);
1579 	}
1580 }
1581 
1582 static int
pf_state_key_ctor(void * mem,int size,void * arg,int flags)1583 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1584 {
1585 	struct pf_state_key *sk = mem;
1586 
1587 	bzero(sk, sizeof(struct pf_state_key_cmp));
1588 	TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1589 	TAILQ_INIT(&sk->states[PF_SK_STACK]);
1590 
1591 	return (0);
1592 }
1593 
1594 static int
pf_state_key_addr_setup(struct pf_pdesc * pd,struct pf_state_key_cmp * key,int multi)1595 pf_state_key_addr_setup(struct pf_pdesc *pd,
1596     struct pf_state_key_cmp *key, int multi)
1597 {
1598 	struct pf_addr *saddr = pd->src;
1599 	struct pf_addr *daddr = pd->dst;
1600 #ifdef INET6
1601 	struct nd_neighbor_solicit nd;
1602 	struct pf_addr *target;
1603 	u_short action, reason;
1604 
1605 	if (pd->af == AF_INET || pd->proto != IPPROTO_ICMPV6)
1606 		goto copy;
1607 
1608 	switch (pd->hdr.icmp6.icmp6_type) {
1609 	case ND_NEIGHBOR_SOLICIT:
1610 		if (multi)
1611 			return (-1);
1612 		if (!pf_pull_hdr(pd->m, pd->off, &nd, sizeof(nd), &action, &reason, pd->af))
1613 			return (-1);
1614 		target = (struct pf_addr *)&nd.nd_ns_target;
1615 		daddr = target;
1616 		break;
1617 	case ND_NEIGHBOR_ADVERT:
1618 		if (multi)
1619 			return (-1);
1620 		if (!pf_pull_hdr(pd->m, pd->off, &nd, sizeof(nd), &action, &reason, pd->af))
1621 			return (-1);
1622 		target = (struct pf_addr *)&nd.nd_ns_target;
1623 		saddr = target;
1624 		if (IN6_IS_ADDR_MULTICAST(&pd->dst->v6)) {
1625 			key->addr[pd->didx].addr32[0] = 0;
1626 			key->addr[pd->didx].addr32[1] = 0;
1627 			key->addr[pd->didx].addr32[2] = 0;
1628 			key->addr[pd->didx].addr32[3] = 0;
1629 			daddr = NULL; /* overwritten */
1630 		}
1631 		break;
1632 	default:
1633 		if (multi == PF_ICMP_MULTI_LINK) {
1634 			key->addr[pd->sidx].addr32[0] = IPV6_ADDR_INT32_MLL;
1635 			key->addr[pd->sidx].addr32[1] = 0;
1636 			key->addr[pd->sidx].addr32[2] = 0;
1637 			key->addr[pd->sidx].addr32[3] = IPV6_ADDR_INT32_ONE;
1638 			saddr = NULL; /* overwritten */
1639 		}
1640 	}
1641 copy:
1642 #endif
1643 	if (saddr)
1644 		PF_ACPY(&key->addr[pd->sidx], saddr, pd->af);
1645 	if (daddr)
1646 		PF_ACPY(&key->addr[pd->didx], daddr, pd->af);
1647 
1648 	return (0);
1649 }
1650 
1651 struct pf_state_key *
pf_state_key_setup(struct pf_pdesc * pd,struct pf_addr * saddr,struct pf_addr * daddr,u_int16_t sport,u_int16_t dport)1652 pf_state_key_setup(struct pf_pdesc *pd,
1653     struct pf_addr *saddr, struct pf_addr *daddr, u_int16_t sport,
1654     u_int16_t dport)
1655 {
1656 	struct pf_state_key *sk;
1657 
1658 	sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1659 	if (sk == NULL)
1660 		return (NULL);
1661 
1662 	if (pf_state_key_addr_setup(pd, (struct pf_state_key_cmp *)sk,
1663 	    0)) {
1664 		uma_zfree(V_pf_state_key_z, sk);
1665 		return (NULL);
1666 	}
1667 
1668 	sk->port[pd->sidx] = sport;
1669 	sk->port[pd->didx] = dport;
1670 	sk->proto = pd->proto;
1671 	sk->af = pd->af;
1672 
1673 	return (sk);
1674 }
1675 
1676 struct pf_state_key *
pf_state_key_clone(const struct pf_state_key * orig)1677 pf_state_key_clone(const struct pf_state_key *orig)
1678 {
1679 	struct pf_state_key *sk;
1680 
1681 	sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1682 	if (sk == NULL)
1683 		return (NULL);
1684 
1685 	bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1686 
1687 	return (sk);
1688 }
1689 
1690 int
pf_state_insert(struct pfi_kkif * kif,struct pfi_kkif * orig_kif,struct pf_state_key * skw,struct pf_state_key * sks,struct pf_kstate * s)1691 pf_state_insert(struct pfi_kkif *kif, struct pfi_kkif *orig_kif,
1692     struct pf_state_key *skw, struct pf_state_key *sks, struct pf_kstate *s)
1693 {
1694 	struct pf_idhash *ih;
1695 	struct pf_kstate *cur;
1696 	int error;
1697 
1698 	NET_EPOCH_ASSERT();
1699 
1700 	KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1701 	    ("%s: sks not pristine", __func__));
1702 	KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1703 	    ("%s: skw not pristine", __func__));
1704 	KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1705 
1706 	s->kif = kif;
1707 	s->orig_kif = orig_kif;
1708 
1709 	if (s->id == 0 && s->creatorid == 0) {
1710 		s->id = alloc_unr64(&V_pf_stateid);
1711 		s->id = htobe64(s->id);
1712 		s->creatorid = V_pf_status.hostid;
1713 	}
1714 
1715 	/* Returns with ID locked on success. */
1716 	if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1717 		return (error);
1718 
1719 	ih = &V_pf_idhash[PF_IDHASH(s)];
1720 	PF_HASHROW_ASSERT(ih);
1721 	LIST_FOREACH(cur, &ih->states, entry)
1722 		if (cur->id == s->id && cur->creatorid == s->creatorid)
1723 			break;
1724 
1725 	if (cur != NULL) {
1726 		s->timeout = PFTM_UNLINKED;
1727 		PF_HASHROW_UNLOCK(ih);
1728 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1729 			printf("pf: state ID collision: "
1730 			    "id: %016llx creatorid: %08x\n",
1731 			    (unsigned long long)be64toh(s->id),
1732 			    ntohl(s->creatorid));
1733 		}
1734 		pf_detach_state(s);
1735 		return (EEXIST);
1736 	}
1737 	LIST_INSERT_HEAD(&ih->states, s, entry);
1738 	/* One for keys, one for ID hash. */
1739 	refcount_init(&s->refs, 2);
1740 
1741 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1742 	if (V_pfsync_insert_state_ptr != NULL)
1743 		V_pfsync_insert_state_ptr(s);
1744 
1745 	/* Returns locked. */
1746 	return (0);
1747 }
1748 
1749 /*
1750  * Find state by ID: returns with locked row on success.
1751  */
1752 struct pf_kstate *
pf_find_state_byid(uint64_t id,uint32_t creatorid)1753 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1754 {
1755 	struct pf_idhash *ih;
1756 	struct pf_kstate *s;
1757 
1758 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1759 
1760 	ih = &V_pf_idhash[(be64toh(id) % (V_pf_hashmask + 1))];
1761 
1762 	PF_HASHROW_LOCK(ih);
1763 	LIST_FOREACH(s, &ih->states, entry)
1764 		if (s->id == id && s->creatorid == creatorid)
1765 			break;
1766 
1767 	if (s == NULL)
1768 		PF_HASHROW_UNLOCK(ih);
1769 
1770 	return (s);
1771 }
1772 
1773 /*
1774  * Find state by key.
1775  * Returns with ID hash slot locked on success.
1776  */
1777 static struct pf_kstate *
pf_find_state(struct pfi_kkif * kif,const struct pf_state_key_cmp * key,u_int dir)1778 pf_find_state(struct pfi_kkif *kif, const struct pf_state_key_cmp *key,
1779     u_int dir)
1780 {
1781 	struct pf_keyhash	*kh;
1782 	struct pf_state_key	*sk;
1783 	struct pf_kstate	*s;
1784 	int idx;
1785 
1786 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1787 
1788 	kh = &V_pf_keyhash[pf_hashkey((const struct pf_state_key *)key)];
1789 
1790 	PF_HASHROW_LOCK(kh);
1791 	LIST_FOREACH(sk, &kh->keys, entry)
1792 		if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1793 			break;
1794 	if (sk == NULL) {
1795 		PF_HASHROW_UNLOCK(kh);
1796 		return (NULL);
1797 	}
1798 
1799 	idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1800 
1801 	/* List is sorted, if-bound states before floating ones. */
1802 	TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1803 		if (s->kif == V_pfi_all || s->kif == kif || s->orig_kif == kif) {
1804 			PF_STATE_LOCK(s);
1805 			PF_HASHROW_UNLOCK(kh);
1806 			if (__predict_false(s->timeout >= PFTM_MAX)) {
1807 				/*
1808 				 * State is either being processed by
1809 				 * pf_unlink_state() in an other thread, or
1810 				 * is scheduled for immediate expiry.
1811 				 */
1812 				PF_STATE_UNLOCK(s);
1813 				return (NULL);
1814 			}
1815 			return (s);
1816 		}
1817 	PF_HASHROW_UNLOCK(kh);
1818 
1819 	return (NULL);
1820 }
1821 
1822 /*
1823  * Returns with ID hash slot locked on success.
1824  */
1825 struct pf_kstate *
pf_find_state_all(const struct pf_state_key_cmp * key,u_int dir,int * more)1826 pf_find_state_all(const struct pf_state_key_cmp *key, u_int dir, int *more)
1827 {
1828 	struct pf_keyhash	*kh;
1829 	struct pf_state_key	*sk;
1830 	struct pf_kstate	*s, *ret = NULL;
1831 	int			 idx, inout = 0;
1832 
1833 	if (more != NULL)
1834 		*more = 0;
1835 
1836 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1837 
1838 	kh = &V_pf_keyhash[pf_hashkey((const struct pf_state_key *)key)];
1839 
1840 	PF_HASHROW_LOCK(kh);
1841 	LIST_FOREACH(sk, &kh->keys, entry)
1842 		if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1843 			break;
1844 	if (sk == NULL) {
1845 		PF_HASHROW_UNLOCK(kh);
1846 		return (NULL);
1847 	}
1848 	switch (dir) {
1849 	case PF_IN:
1850 		idx = PF_SK_WIRE;
1851 		break;
1852 	case PF_OUT:
1853 		idx = PF_SK_STACK;
1854 		break;
1855 	case PF_INOUT:
1856 		idx = PF_SK_WIRE;
1857 		inout = 1;
1858 		break;
1859 	default:
1860 		panic("%s: dir %u", __func__, dir);
1861 	}
1862 second_run:
1863 	TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1864 		if (more == NULL) {
1865 			PF_STATE_LOCK(s);
1866 			PF_HASHROW_UNLOCK(kh);
1867 			return (s);
1868 		}
1869 
1870 		if (ret)
1871 			(*more)++;
1872 		else {
1873 			ret = s;
1874 			PF_STATE_LOCK(s);
1875 		}
1876 	}
1877 	if (inout == 1) {
1878 		inout = 0;
1879 		idx = PF_SK_STACK;
1880 		goto second_run;
1881 	}
1882 	PF_HASHROW_UNLOCK(kh);
1883 
1884 	return (ret);
1885 }
1886 
1887 /*
1888  * FIXME
1889  * This routine is inefficient -- locks the state only to unlock immediately on
1890  * return.
1891  * It is racy -- after the state is unlocked nothing stops other threads from
1892  * removing it.
1893  */
1894 bool
pf_find_state_all_exists(const struct pf_state_key_cmp * key,u_int dir)1895 pf_find_state_all_exists(const struct pf_state_key_cmp *key, u_int dir)
1896 {
1897 	struct pf_kstate *s;
1898 
1899 	s = pf_find_state_all(key, dir, NULL);
1900 	if (s != NULL) {
1901 		PF_STATE_UNLOCK(s);
1902 		return (true);
1903 	}
1904 	return (false);
1905 }
1906 
1907 struct pf_udp_mapping *
pf_udp_mapping_create(sa_family_t af,struct pf_addr * src_addr,uint16_t src_port,struct pf_addr * nat_addr,uint16_t nat_port)1908 pf_udp_mapping_create(sa_family_t af, struct pf_addr *src_addr, uint16_t src_port,
1909     struct pf_addr *nat_addr, uint16_t nat_port)
1910 {
1911 	struct pf_udp_mapping *mapping;
1912 
1913 	mapping = uma_zalloc(V_pf_udp_mapping_z, M_NOWAIT | M_ZERO);
1914 	if (mapping == NULL)
1915 		return (NULL);
1916 	PF_ACPY(&mapping->endpoints[0].addr, src_addr, af);
1917 	mapping->endpoints[0].port = src_port;
1918 	mapping->endpoints[0].af = af;
1919 	mapping->endpoints[0].mapping = mapping;
1920 	PF_ACPY(&mapping->endpoints[1].addr, nat_addr, af);
1921 	mapping->endpoints[1].port = nat_port;
1922 	mapping->endpoints[1].af = af;
1923 	mapping->endpoints[1].mapping = mapping;
1924 	refcount_init(&mapping->refs, 1);
1925 	return (mapping);
1926 }
1927 
1928 int
pf_udp_mapping_insert(struct pf_udp_mapping * mapping)1929 pf_udp_mapping_insert(struct pf_udp_mapping *mapping)
1930 {
1931 	struct pf_udpendpointhash *h0, *h1;
1932 	struct pf_udp_endpoint *endpoint;
1933 	int ret = EEXIST;
1934 
1935 	h0 = &V_pf_udpendpointhash[pf_hashudpendpoint(&mapping->endpoints[0])];
1936 	h1 = &V_pf_udpendpointhash[pf_hashudpendpoint(&mapping->endpoints[1])];
1937 	if (h0 == h1) {
1938 		PF_HASHROW_LOCK(h0);
1939 	} else if (h0 < h1) {
1940 		PF_HASHROW_LOCK(h0);
1941 		PF_HASHROW_LOCK(h1);
1942 	} else {
1943 		PF_HASHROW_LOCK(h1);
1944 		PF_HASHROW_LOCK(h0);
1945 	}
1946 
1947 	LIST_FOREACH(endpoint, &h0->endpoints, entry) {
1948 		if (bcmp(endpoint, &mapping->endpoints[0],
1949 		    sizeof(struct pf_udp_endpoint_cmp)) == 0)
1950 			break;
1951 	}
1952 	if (endpoint != NULL)
1953 		goto cleanup;
1954 	LIST_FOREACH(endpoint, &h1->endpoints, entry) {
1955 		if (bcmp(endpoint, &mapping->endpoints[1],
1956 		    sizeof(struct pf_udp_endpoint_cmp)) == 0)
1957 			break;
1958 	}
1959 	if (endpoint != NULL)
1960 		goto cleanup;
1961 	LIST_INSERT_HEAD(&h0->endpoints, &mapping->endpoints[0], entry);
1962 	LIST_INSERT_HEAD(&h1->endpoints, &mapping->endpoints[1], entry);
1963 	ret = 0;
1964 
1965 cleanup:
1966 	if (h0 != h1) {
1967 		PF_HASHROW_UNLOCK(h0);
1968 		PF_HASHROW_UNLOCK(h1);
1969 	} else {
1970 		PF_HASHROW_UNLOCK(h0);
1971 	}
1972 	return (ret);
1973 }
1974 
1975 void
pf_udp_mapping_release(struct pf_udp_mapping * mapping)1976 pf_udp_mapping_release(struct pf_udp_mapping *mapping)
1977 {
1978 	/* refcount is synchronized on the source endpoint's row lock */
1979 	struct pf_udpendpointhash *h0, *h1;
1980 
1981 	if (mapping == NULL)
1982 		return;
1983 
1984 	h0 = &V_pf_udpendpointhash[pf_hashudpendpoint(&mapping->endpoints[0])];
1985 	PF_HASHROW_LOCK(h0);
1986 	if (refcount_release(&mapping->refs)) {
1987 		LIST_REMOVE(&mapping->endpoints[0], entry);
1988 		PF_HASHROW_UNLOCK(h0);
1989 		h1 = &V_pf_udpendpointhash[pf_hashudpendpoint(&mapping->endpoints[1])];
1990 		PF_HASHROW_LOCK(h1);
1991 		LIST_REMOVE(&mapping->endpoints[1], entry);
1992 		PF_HASHROW_UNLOCK(h1);
1993 
1994 		uma_zfree(V_pf_udp_mapping_z, mapping);
1995 	} else {
1996 			PF_HASHROW_UNLOCK(h0);
1997 	}
1998 }
1999 
2000 
2001 struct pf_udp_mapping *
pf_udp_mapping_find(struct pf_udp_endpoint_cmp * key)2002 pf_udp_mapping_find(struct pf_udp_endpoint_cmp *key)
2003 {
2004 	struct pf_udpendpointhash *uh;
2005 	struct pf_udp_endpoint *endpoint;
2006 
2007 	uh = &V_pf_udpendpointhash[pf_hashudpendpoint((struct pf_udp_endpoint*)key)];
2008 
2009 	PF_HASHROW_LOCK(uh);
2010 	LIST_FOREACH(endpoint, &uh->endpoints, entry) {
2011 		if (bcmp(endpoint, key, sizeof(struct pf_udp_endpoint_cmp)) == 0 &&
2012 			bcmp(endpoint, &endpoint->mapping->endpoints[0],
2013 			    sizeof(struct pf_udp_endpoint_cmp)) == 0)
2014 			break;
2015 	}
2016 	if (endpoint == NULL) {
2017 		PF_HASHROW_UNLOCK(uh);
2018 		return (NULL);
2019 	}
2020 	refcount_acquire(&endpoint->mapping->refs);
2021 	PF_HASHROW_UNLOCK(uh);
2022 	return (endpoint->mapping);
2023 }
2024 /* END state table stuff */
2025 
2026 static void
pf_send(struct pf_send_entry * pfse)2027 pf_send(struct pf_send_entry *pfse)
2028 {
2029 
2030 	PF_SENDQ_LOCK();
2031 	STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
2032 	PF_SENDQ_UNLOCK();
2033 	swi_sched(V_pf_swi_cookie, 0);
2034 }
2035 
2036 static bool
pf_isforlocal(struct mbuf * m,int af)2037 pf_isforlocal(struct mbuf *m, int af)
2038 {
2039 	switch (af) {
2040 #ifdef INET
2041 	case AF_INET: {
2042 		struct ip *ip = mtod(m, struct ip *);
2043 
2044 		return (in_localip(ip->ip_dst));
2045 	}
2046 #endif
2047 #ifdef INET6
2048 	case AF_INET6: {
2049 		struct ip6_hdr *ip6;
2050 		struct in6_ifaddr *ia;
2051 		ip6 = mtod(m, struct ip6_hdr *);
2052 		ia = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
2053 		if (ia == NULL)
2054 			return (false);
2055 		return (! (ia->ia6_flags & IN6_IFF_NOTREADY));
2056 	}
2057 #endif
2058 	}
2059 
2060 	return (false);
2061 }
2062 
2063 int
pf_icmp_mapping(struct pf_pdesc * pd,u_int8_t type,int * icmp_dir,int * multi,u_int16_t * virtual_id,u_int16_t * virtual_type)2064 pf_icmp_mapping(struct pf_pdesc *pd, u_int8_t type,
2065     int *icmp_dir, int *multi, u_int16_t *virtual_id, u_int16_t *virtual_type)
2066 {
2067 	/*
2068 	 * ICMP types marked with PF_OUT are typically responses to
2069 	 * PF_IN, and will match states in the opposite direction.
2070 	 * PF_IN ICMP types need to match a state with that type.
2071 	 */
2072 	*icmp_dir = PF_OUT;
2073 	*multi = PF_ICMP_MULTI_LINK;
2074 	/* Queries (and responses) */
2075 	switch (pd->af) {
2076 #ifdef INET
2077 	case AF_INET:
2078 		switch (type) {
2079 		case ICMP_ECHO:
2080 			*icmp_dir = PF_IN;
2081 		case ICMP_ECHOREPLY:
2082 			*virtual_type = ICMP_ECHO;
2083 			*virtual_id = pd->hdr.icmp.icmp_id;
2084 			break;
2085 
2086 		case ICMP_TSTAMP:
2087 			*icmp_dir = PF_IN;
2088 		case ICMP_TSTAMPREPLY:
2089 			*virtual_type = ICMP_TSTAMP;
2090 			*virtual_id = pd->hdr.icmp.icmp_id;
2091 			break;
2092 
2093 		case ICMP_IREQ:
2094 			*icmp_dir = PF_IN;
2095 		case ICMP_IREQREPLY:
2096 			*virtual_type = ICMP_IREQ;
2097 			*virtual_id = pd->hdr.icmp.icmp_id;
2098 			break;
2099 
2100 		case ICMP_MASKREQ:
2101 			*icmp_dir = PF_IN;
2102 		case ICMP_MASKREPLY:
2103 			*virtual_type = ICMP_MASKREQ;
2104 			*virtual_id = pd->hdr.icmp.icmp_id;
2105 			break;
2106 
2107 		case ICMP_IPV6_WHEREAREYOU:
2108 			*icmp_dir = PF_IN;
2109 		case ICMP_IPV6_IAMHERE:
2110 			*virtual_type = ICMP_IPV6_WHEREAREYOU;
2111 			*virtual_id = 0; /* Nothing sane to match on! */
2112 			break;
2113 
2114 		case ICMP_MOBILE_REGREQUEST:
2115 			*icmp_dir = PF_IN;
2116 		case ICMP_MOBILE_REGREPLY:
2117 			*virtual_type = ICMP_MOBILE_REGREQUEST;
2118 			*virtual_id = 0; /* Nothing sane to match on! */
2119 			break;
2120 
2121 		case ICMP_ROUTERSOLICIT:
2122 			*icmp_dir = PF_IN;
2123 		case ICMP_ROUTERADVERT:
2124 			*virtual_type = ICMP_ROUTERSOLICIT;
2125 			*virtual_id = 0; /* Nothing sane to match on! */
2126 			break;
2127 
2128 		/* These ICMP types map to other connections */
2129 		case ICMP_UNREACH:
2130 		case ICMP_SOURCEQUENCH:
2131 		case ICMP_REDIRECT:
2132 		case ICMP_TIMXCEED:
2133 		case ICMP_PARAMPROB:
2134 			/* These will not be used, but set them anyway */
2135 			*icmp_dir = PF_IN;
2136 			*virtual_type = type;
2137 			*virtual_id = 0;
2138 			HTONS(*virtual_type);
2139 			return (1);  /* These types match to another state */
2140 
2141 		/*
2142 		 * All remaining ICMP types get their own states,
2143 		 * and will only match in one direction.
2144 		 */
2145 		default:
2146 			*icmp_dir = PF_IN;
2147 			*virtual_type = type;
2148 			*virtual_id = 0;
2149 			break;
2150 		}
2151 		break;
2152 #endif /* INET */
2153 #ifdef INET6
2154 	case AF_INET6:
2155 		switch (type) {
2156 		case ICMP6_ECHO_REQUEST:
2157 			*icmp_dir = PF_IN;
2158 		case ICMP6_ECHO_REPLY:
2159 			*virtual_type = ICMP6_ECHO_REQUEST;
2160 			*virtual_id = pd->hdr.icmp6.icmp6_id;
2161 			break;
2162 
2163 		case MLD_LISTENER_QUERY:
2164 		case MLD_LISTENER_REPORT: {
2165 			/*
2166 			 * Listener Report can be sent by clients
2167 			 * without an associated Listener Query.
2168 			 * In addition to that, when Report is sent as a
2169 			 * reply to a Query its source and destination
2170 			 * address are different.
2171 			 */
2172 			*icmp_dir = PF_IN;
2173 			*virtual_type = MLD_LISTENER_QUERY;
2174 			*virtual_id = 0;
2175 			break;
2176 		}
2177 		case MLD_MTRACE:
2178 			*icmp_dir = PF_IN;
2179 		case MLD_MTRACE_RESP:
2180 			*virtual_type = MLD_MTRACE;
2181 			*virtual_id = 0; /* Nothing sane to match on! */
2182 			break;
2183 
2184 		case ND_NEIGHBOR_SOLICIT:
2185 			*icmp_dir = PF_IN;
2186 		case ND_NEIGHBOR_ADVERT: {
2187 			*virtual_type = ND_NEIGHBOR_SOLICIT;
2188 			*virtual_id = 0;
2189 			break;
2190 		}
2191 
2192 		/*
2193 		 * These ICMP types map to other connections.
2194 		 * ND_REDIRECT can't be in this list because the triggering
2195 		 * packet header is optional.
2196 		 */
2197 		case ICMP6_DST_UNREACH:
2198 		case ICMP6_PACKET_TOO_BIG:
2199 		case ICMP6_TIME_EXCEEDED:
2200 		case ICMP6_PARAM_PROB:
2201 			/* These will not be used, but set them anyway */
2202 			*icmp_dir = PF_IN;
2203 			*virtual_type = type;
2204 			*virtual_id = 0;
2205 			HTONS(*virtual_type);
2206 			return (1);  /* These types match to another state */
2207 		/*
2208 		 * All remaining ICMP6 types get their own states,
2209 		 * and will only match in one direction.
2210 		 */
2211 		default:
2212 			*icmp_dir = PF_IN;
2213 			*virtual_type = type;
2214 			*virtual_id = 0;
2215 			break;
2216 		}
2217 		break;
2218 #endif /* INET6 */
2219 	}
2220 	HTONS(*virtual_type);
2221 	return (0);  /* These types match to their own state */
2222 }
2223 
2224 void
pf_intr(void * v)2225 pf_intr(void *v)
2226 {
2227 	struct epoch_tracker et;
2228 	struct pf_send_head queue;
2229 	struct pf_send_entry *pfse, *next;
2230 
2231 	CURVNET_SET((struct vnet *)v);
2232 
2233 	PF_SENDQ_LOCK();
2234 	queue = V_pf_sendqueue;
2235 	STAILQ_INIT(&V_pf_sendqueue);
2236 	PF_SENDQ_UNLOCK();
2237 
2238 	NET_EPOCH_ENTER(et);
2239 
2240 	STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
2241 		switch (pfse->pfse_type) {
2242 #ifdef INET
2243 		case PFSE_IP: {
2244 			if (pf_isforlocal(pfse->pfse_m, AF_INET)) {
2245 				KASSERT(pfse->pfse_m->m_pkthdr.rcvif == V_loif,
2246 				    ("%s: rcvif != loif", __func__));
2247 
2248 				pfse->pfse_m->m_flags |= M_SKIP_FIREWALL;
2249 				pfse->pfse_m->m_pkthdr.csum_flags |=
2250 				    CSUM_IP_VALID | CSUM_IP_CHECKED;
2251 				ip_input(pfse->pfse_m);
2252 			} else {
2253 				ip_output(pfse->pfse_m, NULL, NULL, 0, NULL,
2254 				    NULL);
2255 			}
2256 			break;
2257 		}
2258 		case PFSE_ICMP:
2259 			icmp_error(pfse->pfse_m, pfse->icmpopts.type,
2260 			    pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
2261 			break;
2262 #endif /* INET */
2263 #ifdef INET6
2264 		case PFSE_IP6:
2265 			if (pf_isforlocal(pfse->pfse_m, AF_INET6)) {
2266 				KASSERT(pfse->pfse_m->m_pkthdr.rcvif == V_loif,
2267 				    ("%s: rcvif != loif", __func__));
2268 
2269 				pfse->pfse_m->m_flags |= M_SKIP_FIREWALL |
2270 				    M_LOOP;
2271 				ip6_input(pfse->pfse_m);
2272 			} else {
2273 				ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL,
2274 				    NULL, NULL);
2275 			}
2276 			break;
2277 		case PFSE_ICMP6:
2278 			icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
2279 			    pfse->icmpopts.code, pfse->icmpopts.mtu);
2280 			break;
2281 #endif /* INET6 */
2282 		default:
2283 			panic("%s: unknown type", __func__);
2284 		}
2285 		free(pfse, M_PFTEMP);
2286 	}
2287 	NET_EPOCH_EXIT(et);
2288 	CURVNET_RESTORE();
2289 }
2290 
2291 #define	pf_purge_thread_period	(hz / 10)
2292 
2293 #ifdef PF_WANT_32_TO_64_COUNTER
2294 static void
pf_status_counter_u64_periodic(void)2295 pf_status_counter_u64_periodic(void)
2296 {
2297 
2298 	PF_RULES_RASSERT();
2299 
2300 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 60)) != 0) {
2301 		return;
2302 	}
2303 
2304 	for (int i = 0; i < FCNT_MAX; i++) {
2305 		pf_counter_u64_periodic(&V_pf_status.fcounters[i]);
2306 	}
2307 }
2308 
2309 static void
pf_kif_counter_u64_periodic(void)2310 pf_kif_counter_u64_periodic(void)
2311 {
2312 	struct pfi_kkif *kif;
2313 	size_t r, run;
2314 
2315 	PF_RULES_RASSERT();
2316 
2317 	if (__predict_false(V_pf_allkifcount == 0)) {
2318 		return;
2319 	}
2320 
2321 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 300)) != 0) {
2322 		return;
2323 	}
2324 
2325 	run = V_pf_allkifcount / 10;
2326 	if (run < 5)
2327 		run = 5;
2328 
2329 	for (r = 0; r < run; r++) {
2330 		kif = LIST_NEXT(V_pf_kifmarker, pfik_allkiflist);
2331 		if (kif == NULL) {
2332 			LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
2333 			LIST_INSERT_HEAD(&V_pf_allkiflist, V_pf_kifmarker, pfik_allkiflist);
2334 			break;
2335 		}
2336 
2337 		LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
2338 		LIST_INSERT_AFTER(kif, V_pf_kifmarker, pfik_allkiflist);
2339 
2340 		for (int i = 0; i < 2; i++) {
2341 			for (int j = 0; j < 2; j++) {
2342 				for (int k = 0; k < 2; k++) {
2343 					pf_counter_u64_periodic(&kif->pfik_packets[i][j][k]);
2344 					pf_counter_u64_periodic(&kif->pfik_bytes[i][j][k]);
2345 				}
2346 			}
2347 		}
2348 	}
2349 }
2350 
2351 static void
pf_rule_counter_u64_periodic(void)2352 pf_rule_counter_u64_periodic(void)
2353 {
2354 	struct pf_krule *rule;
2355 	size_t r, run;
2356 
2357 	PF_RULES_RASSERT();
2358 
2359 	if (__predict_false(V_pf_allrulecount == 0)) {
2360 		return;
2361 	}
2362 
2363 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 300)) != 0) {
2364 		return;
2365 	}
2366 
2367 	run = V_pf_allrulecount / 10;
2368 	if (run < 5)
2369 		run = 5;
2370 
2371 	for (r = 0; r < run; r++) {
2372 		rule = LIST_NEXT(V_pf_rulemarker, allrulelist);
2373 		if (rule == NULL) {
2374 			LIST_REMOVE(V_pf_rulemarker, allrulelist);
2375 			LIST_INSERT_HEAD(&V_pf_allrulelist, V_pf_rulemarker, allrulelist);
2376 			break;
2377 		}
2378 
2379 		LIST_REMOVE(V_pf_rulemarker, allrulelist);
2380 		LIST_INSERT_AFTER(rule, V_pf_rulemarker, allrulelist);
2381 
2382 		pf_counter_u64_periodic(&rule->evaluations);
2383 		for (int i = 0; i < 2; i++) {
2384 			pf_counter_u64_periodic(&rule->packets[i]);
2385 			pf_counter_u64_periodic(&rule->bytes[i]);
2386 		}
2387 	}
2388 }
2389 
2390 static void
pf_counter_u64_periodic_main(void)2391 pf_counter_u64_periodic_main(void)
2392 {
2393 	PF_RULES_RLOCK_TRACKER;
2394 
2395 	V_pf_counter_periodic_iter++;
2396 
2397 	PF_RULES_RLOCK();
2398 	pf_counter_u64_critical_enter();
2399 	pf_status_counter_u64_periodic();
2400 	pf_kif_counter_u64_periodic();
2401 	pf_rule_counter_u64_periodic();
2402 	pf_counter_u64_critical_exit();
2403 	PF_RULES_RUNLOCK();
2404 }
2405 #else
2406 #define	pf_counter_u64_periodic_main()	do { } while (0)
2407 #endif
2408 
2409 void
pf_purge_thread(void * unused __unused)2410 pf_purge_thread(void *unused __unused)
2411 {
2412 	struct epoch_tracker	 et;
2413 
2414 	VNET_ITERATOR_DECL(vnet_iter);
2415 
2416 	sx_xlock(&pf_end_lock);
2417 	while (pf_end_threads == 0) {
2418 		sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", pf_purge_thread_period);
2419 
2420 		VNET_LIST_RLOCK();
2421 		NET_EPOCH_ENTER(et);
2422 		VNET_FOREACH(vnet_iter) {
2423 			CURVNET_SET(vnet_iter);
2424 
2425 			/* Wait until V_pf_default_rule is initialized. */
2426 			if (V_pf_vnet_active == 0) {
2427 				CURVNET_RESTORE();
2428 				continue;
2429 			}
2430 
2431 			pf_counter_u64_periodic_main();
2432 
2433 			/*
2434 			 *  Process 1/interval fraction of the state
2435 			 * table every run.
2436 			 */
2437 			V_pf_purge_idx =
2438 			    pf_purge_expired_states(V_pf_purge_idx, V_pf_hashmask /
2439 			    (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
2440 
2441 			/*
2442 			 * Purge other expired types every
2443 			 * PFTM_INTERVAL seconds.
2444 			 */
2445 			if (V_pf_purge_idx == 0) {
2446 				/*
2447 				 * Order is important:
2448 				 * - states and src nodes reference rules
2449 				 * - states and rules reference kifs
2450 				 */
2451 				pf_purge_expired_fragments();
2452 				pf_purge_expired_src_nodes();
2453 				pf_purge_unlinked_rules();
2454 				pfi_kkif_purge();
2455 			}
2456 			CURVNET_RESTORE();
2457 		}
2458 		NET_EPOCH_EXIT(et);
2459 		VNET_LIST_RUNLOCK();
2460 	}
2461 
2462 	pf_end_threads++;
2463 	sx_xunlock(&pf_end_lock);
2464 	kproc_exit(0);
2465 }
2466 
2467 void
pf_unload_vnet_purge(void)2468 pf_unload_vnet_purge(void)
2469 {
2470 
2471 	/*
2472 	 * To cleanse up all kifs and rules we need
2473 	 * two runs: first one clears reference flags,
2474 	 * then pf_purge_expired_states() doesn't
2475 	 * raise them, and then second run frees.
2476 	 */
2477 	pf_purge_unlinked_rules();
2478 	pfi_kkif_purge();
2479 
2480 	/*
2481 	 * Now purge everything.
2482 	 */
2483 	pf_purge_expired_states(0, V_pf_hashmask);
2484 	pf_purge_fragments(UINT_MAX);
2485 	pf_purge_expired_src_nodes();
2486 
2487 	/*
2488 	 * Now all kifs & rules should be unreferenced,
2489 	 * thus should be successfully freed.
2490 	 */
2491 	pf_purge_unlinked_rules();
2492 	pfi_kkif_purge();
2493 }
2494 
2495 u_int32_t
pf_state_expires(const struct pf_kstate * state)2496 pf_state_expires(const struct pf_kstate *state)
2497 {
2498 	u_int32_t	timeout;
2499 	u_int32_t	start;
2500 	u_int32_t	end;
2501 	u_int32_t	states;
2502 
2503 	/* handle all PFTM_* > PFTM_MAX here */
2504 	if (state->timeout == PFTM_PURGE)
2505 		return (time_uptime);
2506 	KASSERT(state->timeout != PFTM_UNLINKED,
2507 	    ("pf_state_expires: timeout == PFTM_UNLINKED"));
2508 	KASSERT((state->timeout < PFTM_MAX),
2509 	    ("pf_state_expires: timeout > PFTM_MAX"));
2510 	timeout = state->rule->timeout[state->timeout];
2511 	if (!timeout)
2512 		timeout = V_pf_default_rule.timeout[state->timeout];
2513 	start = state->rule->timeout[PFTM_ADAPTIVE_START];
2514 	if (start && state->rule != &V_pf_default_rule) {
2515 		end = state->rule->timeout[PFTM_ADAPTIVE_END];
2516 		states = counter_u64_fetch(state->rule->states_cur);
2517 	} else {
2518 		start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
2519 		end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
2520 		states = V_pf_status.states;
2521 	}
2522 	if (end && states > start && start < end) {
2523 		if (states < end) {
2524 			timeout = (u_int64_t)timeout * (end - states) /
2525 			    (end - start);
2526 			return ((state->expire / 1000) + timeout);
2527 		}
2528 		else
2529 			return (time_uptime);
2530 	}
2531 	return ((state->expire / 1000) + timeout);
2532 }
2533 
2534 void
pf_purge_expired_src_nodes(void)2535 pf_purge_expired_src_nodes(void)
2536 {
2537 	struct pf_ksrc_node_list	 freelist;
2538 	struct pf_srchash	*sh;
2539 	struct pf_ksrc_node	*cur, *next;
2540 	int i;
2541 
2542 	LIST_INIT(&freelist);
2543 	for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
2544 	    PF_HASHROW_LOCK(sh);
2545 	    LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
2546 		if (cur->states == 0 && cur->expire <= time_uptime) {
2547 			pf_unlink_src_node(cur);
2548 			LIST_INSERT_HEAD(&freelist, cur, entry);
2549 		} else if (cur->rule != NULL)
2550 			cur->rule->rule_ref |= PFRULE_REFS;
2551 	    PF_HASHROW_UNLOCK(sh);
2552 	}
2553 
2554 	pf_free_src_nodes(&freelist);
2555 
2556 	V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
2557 }
2558 
2559 static void
pf_src_tree_remove_state(struct pf_kstate * s)2560 pf_src_tree_remove_state(struct pf_kstate *s)
2561 {
2562 	struct pf_ksrc_node *sn;
2563 	uint32_t timeout;
2564 
2565 	timeout = s->rule->timeout[PFTM_SRC_NODE] ?
2566 	    s->rule->timeout[PFTM_SRC_NODE] :
2567 	    V_pf_default_rule.timeout[PFTM_SRC_NODE];
2568 
2569 	if (s->src_node != NULL) {
2570 		sn = s->src_node;
2571 		PF_SRC_NODE_LOCK(sn);
2572 		if (s->src.tcp_est)
2573 			--sn->conn;
2574 		if (--sn->states == 0)
2575 			sn->expire = time_uptime + timeout;
2576 		PF_SRC_NODE_UNLOCK(sn);
2577 	}
2578 	if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
2579 		sn = s->nat_src_node;
2580 		PF_SRC_NODE_LOCK(sn);
2581 		if (--sn->states == 0)
2582 			sn->expire = time_uptime + timeout;
2583 		PF_SRC_NODE_UNLOCK(sn);
2584 	}
2585 	s->src_node = s->nat_src_node = NULL;
2586 }
2587 
2588 /*
2589  * Unlink and potentilly free a state. Function may be
2590  * called with ID hash row locked, but always returns
2591  * unlocked, since it needs to go through key hash locking.
2592  */
2593 int
pf_unlink_state(struct pf_kstate * s)2594 pf_unlink_state(struct pf_kstate *s)
2595 {
2596 	struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
2597 
2598 	NET_EPOCH_ASSERT();
2599 	PF_HASHROW_ASSERT(ih);
2600 
2601 	if (s->timeout == PFTM_UNLINKED) {
2602 		/*
2603 		 * State is being processed
2604 		 * by pf_unlink_state() in
2605 		 * an other thread.
2606 		 */
2607 		PF_HASHROW_UNLOCK(ih);
2608 		return (0);	/* XXXGL: undefined actually */
2609 	}
2610 
2611 	if (s->src.state == PF_TCPS_PROXY_DST) {
2612 		/* XXX wire key the right one? */
2613 		pf_send_tcp(s->rule, s->key[PF_SK_WIRE]->af,
2614 		    &s->key[PF_SK_WIRE]->addr[1],
2615 		    &s->key[PF_SK_WIRE]->addr[0],
2616 		    s->key[PF_SK_WIRE]->port[1],
2617 		    s->key[PF_SK_WIRE]->port[0],
2618 		    s->src.seqhi, s->src.seqlo + 1,
2619 		    TH_RST|TH_ACK, 0, 0, 0, M_SKIP_FIREWALL, s->tag, 0,
2620 		    s->act.rtableid);
2621 	}
2622 
2623 	LIST_REMOVE(s, entry);
2624 	pf_src_tree_remove_state(s);
2625 
2626 	if (V_pfsync_delete_state_ptr != NULL)
2627 		V_pfsync_delete_state_ptr(s);
2628 
2629 	STATE_DEC_COUNTERS(s);
2630 
2631 	s->timeout = PFTM_UNLINKED;
2632 
2633 	/* Ensure we remove it from the list of halfopen states, if needed. */
2634 	if (s->key[PF_SK_STACK] != NULL &&
2635 	    s->key[PF_SK_STACK]->proto == IPPROTO_TCP)
2636 		pf_set_protostate(s, PF_PEER_BOTH, TCPS_CLOSED);
2637 
2638 	PF_HASHROW_UNLOCK(ih);
2639 
2640 	pf_detach_state(s);
2641 
2642 	pf_udp_mapping_release(s->udp_mapping);
2643 
2644 	/* pf_state_insert() initialises refs to 2 */
2645 	return (pf_release_staten(s, 2));
2646 }
2647 
2648 struct pf_kstate *
pf_alloc_state(int flags)2649 pf_alloc_state(int flags)
2650 {
2651 
2652 	return (uma_zalloc(V_pf_state_z, flags | M_ZERO));
2653 }
2654 
2655 void
pf_free_state(struct pf_kstate * cur)2656 pf_free_state(struct pf_kstate *cur)
2657 {
2658 	struct pf_krule_item *ri;
2659 
2660 	KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
2661 	KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
2662 	    cur->timeout));
2663 
2664 	while ((ri = SLIST_FIRST(&cur->match_rules))) {
2665 		SLIST_REMOVE_HEAD(&cur->match_rules, entry);
2666 		free(ri, M_PF_RULE_ITEM);
2667 	}
2668 
2669 	pf_normalize_tcp_cleanup(cur);
2670 	uma_zfree(V_pf_state_z, cur);
2671 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
2672 }
2673 
2674 /*
2675  * Called only from pf_purge_thread(), thus serialized.
2676  */
2677 static u_int
pf_purge_expired_states(u_int i,int maxcheck)2678 pf_purge_expired_states(u_int i, int maxcheck)
2679 {
2680 	struct pf_idhash *ih;
2681 	struct pf_kstate *s;
2682 	struct pf_krule_item *mrm;
2683 	size_t count __unused;
2684 
2685 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2686 
2687 	/*
2688 	 * Go through hash and unlink states that expire now.
2689 	 */
2690 	while (maxcheck > 0) {
2691 		count = 0;
2692 		ih = &V_pf_idhash[i];
2693 
2694 		/* only take the lock if we expect to do work */
2695 		if (!LIST_EMPTY(&ih->states)) {
2696 relock:
2697 			PF_HASHROW_LOCK(ih);
2698 			LIST_FOREACH(s, &ih->states, entry) {
2699 				if (pf_state_expires(s) <= time_uptime) {
2700 					V_pf_status.states -=
2701 					    pf_unlink_state(s);
2702 					goto relock;
2703 				}
2704 				s->rule->rule_ref |= PFRULE_REFS;
2705 				if (s->nat_rule != NULL)
2706 					s->nat_rule->rule_ref |= PFRULE_REFS;
2707 				if (s->anchor != NULL)
2708 					s->anchor->rule_ref |= PFRULE_REFS;
2709 				s->kif->pfik_flags |= PFI_IFLAG_REFS;
2710 				SLIST_FOREACH(mrm, &s->match_rules, entry)
2711 					mrm->r->rule_ref |= PFRULE_REFS;
2712 				if (s->rt_kif)
2713 					s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
2714 				count++;
2715 			}
2716 			PF_HASHROW_UNLOCK(ih);
2717 		}
2718 
2719 		SDT_PROBE2(pf, purge, state, rowcount, i, count);
2720 
2721 		/* Return when we hit end of hash. */
2722 		if (++i > V_pf_hashmask) {
2723 			V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2724 			return (0);
2725 		}
2726 
2727 		maxcheck--;
2728 	}
2729 
2730 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2731 
2732 	return (i);
2733 }
2734 
2735 static void
pf_purge_unlinked_rules(void)2736 pf_purge_unlinked_rules(void)
2737 {
2738 	struct pf_krulequeue tmpq;
2739 	struct pf_krule *r, *r1;
2740 
2741 	/*
2742 	 * If we have overloading task pending, then we'd
2743 	 * better skip purging this time. There is a tiny
2744 	 * probability that overloading task references
2745 	 * an already unlinked rule.
2746 	 */
2747 	PF_OVERLOADQ_LOCK();
2748 	if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
2749 		PF_OVERLOADQ_UNLOCK();
2750 		return;
2751 	}
2752 	PF_OVERLOADQ_UNLOCK();
2753 
2754 	/*
2755 	 * Do naive mark-and-sweep garbage collecting of old rules.
2756 	 * Reference flag is raised by pf_purge_expired_states()
2757 	 * and pf_purge_expired_src_nodes().
2758 	 *
2759 	 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
2760 	 * use a temporary queue.
2761 	 */
2762 	TAILQ_INIT(&tmpq);
2763 	PF_UNLNKDRULES_LOCK();
2764 	TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
2765 		if (!(r->rule_ref & PFRULE_REFS)) {
2766 			TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
2767 			TAILQ_INSERT_TAIL(&tmpq, r, entries);
2768 		} else
2769 			r->rule_ref &= ~PFRULE_REFS;
2770 	}
2771 	PF_UNLNKDRULES_UNLOCK();
2772 
2773 	if (!TAILQ_EMPTY(&tmpq)) {
2774 		PF_CONFIG_LOCK();
2775 		PF_RULES_WLOCK();
2776 		TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
2777 			TAILQ_REMOVE(&tmpq, r, entries);
2778 			pf_free_rule(r);
2779 		}
2780 		PF_RULES_WUNLOCK();
2781 		PF_CONFIG_UNLOCK();
2782 	}
2783 }
2784 
2785 void
pf_print_host(struct pf_addr * addr,u_int16_t p,sa_family_t af)2786 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
2787 {
2788 	switch (af) {
2789 #ifdef INET
2790 	case AF_INET: {
2791 		u_int32_t a = ntohl(addr->addr32[0]);
2792 		printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
2793 		    (a>>8)&255, a&255);
2794 		if (p) {
2795 			p = ntohs(p);
2796 			printf(":%u", p);
2797 		}
2798 		break;
2799 	}
2800 #endif /* INET */
2801 #ifdef INET6
2802 	case AF_INET6: {
2803 		u_int16_t b;
2804 		u_int8_t i, curstart, curend, maxstart, maxend;
2805 		curstart = curend = maxstart = maxend = 255;
2806 		for (i = 0; i < 8; i++) {
2807 			if (!addr->addr16[i]) {
2808 				if (curstart == 255)
2809 					curstart = i;
2810 				curend = i;
2811 			} else {
2812 				if ((curend - curstart) >
2813 				    (maxend - maxstart)) {
2814 					maxstart = curstart;
2815 					maxend = curend;
2816 				}
2817 				curstart = curend = 255;
2818 			}
2819 		}
2820 		if ((curend - curstart) >
2821 		    (maxend - maxstart)) {
2822 			maxstart = curstart;
2823 			maxend = curend;
2824 		}
2825 		for (i = 0; i < 8; i++) {
2826 			if (i >= maxstart && i <= maxend) {
2827 				if (i == 0)
2828 					printf(":");
2829 				if (i == maxend)
2830 					printf(":");
2831 			} else {
2832 				b = ntohs(addr->addr16[i]);
2833 				printf("%x", b);
2834 				if (i < 7)
2835 					printf(":");
2836 			}
2837 		}
2838 		if (p) {
2839 			p = ntohs(p);
2840 			printf("[%u]", p);
2841 		}
2842 		break;
2843 	}
2844 #endif /* INET6 */
2845 	}
2846 }
2847 
2848 void
pf_print_state(struct pf_kstate * s)2849 pf_print_state(struct pf_kstate *s)
2850 {
2851 	pf_print_state_parts(s, NULL, NULL);
2852 }
2853 
2854 static void
pf_print_state_parts(struct pf_kstate * s,struct pf_state_key * skwp,struct pf_state_key * sksp)2855 pf_print_state_parts(struct pf_kstate *s,
2856     struct pf_state_key *skwp, struct pf_state_key *sksp)
2857 {
2858 	struct pf_state_key *skw, *sks;
2859 	u_int8_t proto, dir;
2860 
2861 	/* Do our best to fill these, but they're skipped if NULL */
2862 	skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
2863 	sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
2864 	proto = skw ? skw->proto : (sks ? sks->proto : 0);
2865 	dir = s ? s->direction : 0;
2866 
2867 	switch (proto) {
2868 	case IPPROTO_IPV4:
2869 		printf("IPv4");
2870 		break;
2871 	case IPPROTO_IPV6:
2872 		printf("IPv6");
2873 		break;
2874 	case IPPROTO_TCP:
2875 		printf("TCP");
2876 		break;
2877 	case IPPROTO_UDP:
2878 		printf("UDP");
2879 		break;
2880 	case IPPROTO_ICMP:
2881 		printf("ICMP");
2882 		break;
2883 	case IPPROTO_ICMPV6:
2884 		printf("ICMPv6");
2885 		break;
2886 	default:
2887 		printf("%u", proto);
2888 		break;
2889 	}
2890 	switch (dir) {
2891 	case PF_IN:
2892 		printf(" in");
2893 		break;
2894 	case PF_OUT:
2895 		printf(" out");
2896 		break;
2897 	}
2898 	if (skw) {
2899 		printf(" wire: ");
2900 		pf_print_host(&skw->addr[0], skw->port[0], skw->af);
2901 		printf(" ");
2902 		pf_print_host(&skw->addr[1], skw->port[1], skw->af);
2903 	}
2904 	if (sks) {
2905 		printf(" stack: ");
2906 		if (sks != skw) {
2907 			pf_print_host(&sks->addr[0], sks->port[0], sks->af);
2908 			printf(" ");
2909 			pf_print_host(&sks->addr[1], sks->port[1], sks->af);
2910 		} else
2911 			printf("-");
2912 	}
2913 	if (s) {
2914 		if (proto == IPPROTO_TCP) {
2915 			printf(" [lo=%u high=%u win=%u modulator=%u",
2916 			    s->src.seqlo, s->src.seqhi,
2917 			    s->src.max_win, s->src.seqdiff);
2918 			if (s->src.wscale && s->dst.wscale)
2919 				printf(" wscale=%u",
2920 				    s->src.wscale & PF_WSCALE_MASK);
2921 			printf("]");
2922 			printf(" [lo=%u high=%u win=%u modulator=%u",
2923 			    s->dst.seqlo, s->dst.seqhi,
2924 			    s->dst.max_win, s->dst.seqdiff);
2925 			if (s->src.wscale && s->dst.wscale)
2926 				printf(" wscale=%u",
2927 				s->dst.wscale & PF_WSCALE_MASK);
2928 			printf("]");
2929 		}
2930 		printf(" %u:%u", s->src.state, s->dst.state);
2931 		if (s->rule)
2932 			printf(" @%d", s->rule->nr);
2933 	}
2934 }
2935 
2936 void
pf_print_flags(uint16_t f)2937 pf_print_flags(uint16_t f)
2938 {
2939 	if (f)
2940 		printf(" ");
2941 	if (f & TH_FIN)
2942 		printf("F");
2943 	if (f & TH_SYN)
2944 		printf("S");
2945 	if (f & TH_RST)
2946 		printf("R");
2947 	if (f & TH_PUSH)
2948 		printf("P");
2949 	if (f & TH_ACK)
2950 		printf("A");
2951 	if (f & TH_URG)
2952 		printf("U");
2953 	if (f & TH_ECE)
2954 		printf("E");
2955 	if (f & TH_CWR)
2956 		printf("W");
2957 	if (f & TH_AE)
2958 		printf("e");
2959 }
2960 
2961 #define	PF_SET_SKIP_STEPS(i)					\
2962 	do {							\
2963 		while (head[i] != cur) {			\
2964 			head[i]->skip[i] = cur;			\
2965 			head[i] = TAILQ_NEXT(head[i], entries);	\
2966 		}						\
2967 	} while (0)
2968 
2969 void
pf_calc_skip_steps(struct pf_krulequeue * rules)2970 pf_calc_skip_steps(struct pf_krulequeue *rules)
2971 {
2972 	struct pf_krule *cur, *prev, *head[PF_SKIP_COUNT];
2973 	int i;
2974 
2975 	cur = TAILQ_FIRST(rules);
2976 	prev = cur;
2977 	for (i = 0; i < PF_SKIP_COUNT; ++i)
2978 		head[i] = cur;
2979 	while (cur != NULL) {
2980 		if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2981 			PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2982 		if (cur->direction != prev->direction)
2983 			PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2984 		if (cur->af != prev->af)
2985 			PF_SET_SKIP_STEPS(PF_SKIP_AF);
2986 		if (cur->proto != prev->proto)
2987 			PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2988 		if (cur->src.neg != prev->src.neg ||
2989 		    pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2990 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2991 		if (cur->dst.neg != prev->dst.neg ||
2992 		    pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2993 			PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2994 		if (cur->src.port[0] != prev->src.port[0] ||
2995 		    cur->src.port[1] != prev->src.port[1] ||
2996 		    cur->src.port_op != prev->src.port_op)
2997 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2998 		if (cur->dst.port[0] != prev->dst.port[0] ||
2999 		    cur->dst.port[1] != prev->dst.port[1] ||
3000 		    cur->dst.port_op != prev->dst.port_op)
3001 			PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
3002 
3003 		prev = cur;
3004 		cur = TAILQ_NEXT(cur, entries);
3005 	}
3006 	for (i = 0; i < PF_SKIP_COUNT; ++i)
3007 		PF_SET_SKIP_STEPS(i);
3008 }
3009 
3010 int
pf_addr_wrap_neq(struct pf_addr_wrap * aw1,struct pf_addr_wrap * aw2)3011 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
3012 {
3013 	if (aw1->type != aw2->type)
3014 		return (1);
3015 	switch (aw1->type) {
3016 	case PF_ADDR_ADDRMASK:
3017 	case PF_ADDR_RANGE:
3018 		if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
3019 			return (1);
3020 		if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
3021 			return (1);
3022 		return (0);
3023 	case PF_ADDR_DYNIFTL:
3024 		return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
3025 	case PF_ADDR_NOROUTE:
3026 	case PF_ADDR_URPFFAILED:
3027 		return (0);
3028 	case PF_ADDR_TABLE:
3029 		return (aw1->p.tbl != aw2->p.tbl);
3030 	default:
3031 		printf("invalid address type: %d\n", aw1->type);
3032 		return (1);
3033 	}
3034 }
3035 
3036 /**
3037  * Checksum updates are a little complicated because the checksum in the TCP/UDP
3038  * header isn't always a full checksum. In some cases (i.e. output) it's a
3039  * pseudo-header checksum, which is a partial checksum over src/dst IP
3040  * addresses, protocol number and length.
3041  *
3042  * That means we have the following cases:
3043  *  * Input or forwarding: we don't have TSO, the checksum fields are full
3044  *  	checksums, we need to update the checksum whenever we change anything.
3045  *  * Output (i.e. the checksum is a pseudo-header checksum):
3046  *  	x The field being updated is src/dst address or affects the length of
3047  *  	the packet. We need to update the pseudo-header checksum (note that this
3048  *  	checksum is not ones' complement).
3049  *  	x Some other field is being modified (e.g. src/dst port numbers): We
3050  *  	don't have to update anything.
3051  **/
3052 u_int16_t
pf_cksum_fixup(u_int16_t cksum,u_int16_t old,u_int16_t new,u_int8_t udp)3053 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
3054 {
3055 	u_int32_t x;
3056 
3057 	x = cksum + old - new;
3058 	x = (x + (x >> 16)) & 0xffff;
3059 
3060 	/* optimise: eliminate a branch when not udp */
3061 	if (udp && cksum == 0x0000)
3062 		return cksum;
3063 	if (udp && x == 0x0000)
3064 		x = 0xffff;
3065 
3066 	return (u_int16_t)(x);
3067 }
3068 
3069 static void
pf_patch_8(struct mbuf * m,u_int16_t * cksum,u_int8_t * f,u_int8_t v,bool hi,u_int8_t udp)3070 pf_patch_8(struct mbuf *m, u_int16_t *cksum, u_int8_t *f, u_int8_t v, bool hi,
3071     u_int8_t udp)
3072 {
3073 	u_int16_t old = htons(hi ? (*f << 8) : *f);
3074 	u_int16_t new = htons(hi ? ( v << 8) :  v);
3075 
3076 	if (*f == v)
3077 		return;
3078 
3079 	*f = v;
3080 
3081 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
3082 		return;
3083 
3084 	*cksum = pf_cksum_fixup(*cksum, old, new, udp);
3085 }
3086 
3087 void
pf_patch_16_unaligned(struct mbuf * m,u_int16_t * cksum,void * f,u_int16_t v,bool hi,u_int8_t udp)3088 pf_patch_16_unaligned(struct mbuf *m, u_int16_t *cksum, void *f, u_int16_t v,
3089     bool hi, u_int8_t udp)
3090 {
3091 	u_int8_t *fb = (u_int8_t *)f;
3092 	u_int8_t *vb = (u_int8_t *)&v;
3093 
3094 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
3095 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
3096 }
3097 
3098 void
pf_patch_32_unaligned(struct mbuf * m,u_int16_t * cksum,void * f,u_int32_t v,bool hi,u_int8_t udp)3099 pf_patch_32_unaligned(struct mbuf *m, u_int16_t *cksum, void *f, u_int32_t v,
3100     bool hi, u_int8_t udp)
3101 {
3102 	u_int8_t *fb = (u_int8_t *)f;
3103 	u_int8_t *vb = (u_int8_t *)&v;
3104 
3105 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
3106 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
3107 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
3108 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
3109 }
3110 
3111 u_int16_t
pf_proto_cksum_fixup(struct mbuf * m,u_int16_t cksum,u_int16_t old,u_int16_t new,u_int8_t udp)3112 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
3113         u_int16_t new, u_int8_t udp)
3114 {
3115 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
3116 		return (cksum);
3117 
3118 	return (pf_cksum_fixup(cksum, old, new, udp));
3119 }
3120 
3121 static void
pf_change_ap(struct mbuf * m,struct pf_addr * a,u_int16_t * p,u_int16_t * ic,u_int16_t * pc,struct pf_addr * an,u_int16_t pn,u_int8_t u,sa_family_t af)3122 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
3123         u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
3124         sa_family_t af)
3125 {
3126 	struct pf_addr	ao;
3127 	u_int16_t	po = *p;
3128 
3129 	PF_ACPY(&ao, a, af);
3130 	PF_ACPY(a, an, af);
3131 
3132 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
3133 		*pc = ~*pc;
3134 
3135 	*p = pn;
3136 
3137 	switch (af) {
3138 #ifdef INET
3139 	case AF_INET:
3140 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
3141 		    ao.addr16[0], an->addr16[0], 0),
3142 		    ao.addr16[1], an->addr16[1], 0);
3143 		*p = pn;
3144 
3145 		*pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
3146 		    ao.addr16[0], an->addr16[0], u),
3147 		    ao.addr16[1], an->addr16[1], u);
3148 
3149 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
3150 		break;
3151 #endif /* INET */
3152 #ifdef INET6
3153 	case AF_INET6:
3154 		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3155 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3156 		    pf_cksum_fixup(pf_cksum_fixup(*pc,
3157 		    ao.addr16[0], an->addr16[0], u),
3158 		    ao.addr16[1], an->addr16[1], u),
3159 		    ao.addr16[2], an->addr16[2], u),
3160 		    ao.addr16[3], an->addr16[3], u),
3161 		    ao.addr16[4], an->addr16[4], u),
3162 		    ao.addr16[5], an->addr16[5], u),
3163 		    ao.addr16[6], an->addr16[6], u),
3164 		    ao.addr16[7], an->addr16[7], u);
3165 
3166 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
3167 		break;
3168 #endif /* INET6 */
3169 	}
3170 
3171 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
3172 	    CSUM_DELAY_DATA_IPV6)) {
3173 		*pc = ~*pc;
3174 		if (! *pc)
3175 			*pc = 0xffff;
3176 	}
3177 }
3178 
3179 /* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
3180 void
pf_change_a(void * a,u_int16_t * c,u_int32_t an,u_int8_t u)3181 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
3182 {
3183 	u_int32_t	ao;
3184 
3185 	memcpy(&ao, a, sizeof(ao));
3186 	memcpy(a, &an, sizeof(u_int32_t));
3187 	*c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
3188 	    ao % 65536, an % 65536, u);
3189 }
3190 
3191 void
pf_change_proto_a(struct mbuf * m,void * a,u_int16_t * c,u_int32_t an,u_int8_t udp)3192 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
3193 {
3194 	u_int32_t	ao;
3195 
3196 	memcpy(&ao, a, sizeof(ao));
3197 	memcpy(a, &an, sizeof(u_int32_t));
3198 
3199 	*c = pf_proto_cksum_fixup(m,
3200 	    pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
3201 	    ao % 65536, an % 65536, udp);
3202 }
3203 
3204 #ifdef INET6
3205 static void
pf_change_a6(struct pf_addr * a,u_int16_t * c,struct pf_addr * an,u_int8_t u)3206 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
3207 {
3208 	struct pf_addr	ao;
3209 
3210 	PF_ACPY(&ao, a, AF_INET6);
3211 	PF_ACPY(a, an, AF_INET6);
3212 
3213 	*c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3214 	    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3215 	    pf_cksum_fixup(pf_cksum_fixup(*c,
3216 	    ao.addr16[0], an->addr16[0], u),
3217 	    ao.addr16[1], an->addr16[1], u),
3218 	    ao.addr16[2], an->addr16[2], u),
3219 	    ao.addr16[3], an->addr16[3], u),
3220 	    ao.addr16[4], an->addr16[4], u),
3221 	    ao.addr16[5], an->addr16[5], u),
3222 	    ao.addr16[6], an->addr16[6], u),
3223 	    ao.addr16[7], an->addr16[7], u);
3224 }
3225 #endif /* INET6 */
3226 
3227 static void
pf_change_icmp(struct pf_addr * ia,u_int16_t * ip,struct pf_addr * oa,struct pf_addr * na,u_int16_t np,u_int16_t * pc,u_int16_t * h2c,u_int16_t * ic,u_int16_t * hc,u_int8_t u,sa_family_t af)3228 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
3229     struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
3230     u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
3231 {
3232 	struct pf_addr	oia, ooa;
3233 
3234 	PF_ACPY(&oia, ia, af);
3235 	if (oa)
3236 		PF_ACPY(&ooa, oa, af);
3237 
3238 	/* Change inner protocol port, fix inner protocol checksum. */
3239 	if (ip != NULL) {
3240 		u_int16_t	oip = *ip;
3241 		u_int32_t	opc;
3242 
3243 		if (pc != NULL)
3244 			opc = *pc;
3245 		*ip = np;
3246 		if (pc != NULL)
3247 			*pc = pf_cksum_fixup(*pc, oip, *ip, u);
3248 		*ic = pf_cksum_fixup(*ic, oip, *ip, 0);
3249 		if (pc != NULL)
3250 			*ic = pf_cksum_fixup(*ic, opc, *pc, 0);
3251 	}
3252 	/* Change inner ip address, fix inner ip and icmp checksums. */
3253 	PF_ACPY(ia, na, af);
3254 	switch (af) {
3255 #ifdef INET
3256 	case AF_INET: {
3257 		u_int32_t	 oh2c = *h2c;
3258 
3259 		*h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
3260 		    oia.addr16[0], ia->addr16[0], 0),
3261 		    oia.addr16[1], ia->addr16[1], 0);
3262 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
3263 		    oia.addr16[0], ia->addr16[0], 0),
3264 		    oia.addr16[1], ia->addr16[1], 0);
3265 		*ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
3266 		break;
3267 	}
3268 #endif /* INET */
3269 #ifdef INET6
3270 	case AF_INET6:
3271 		*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3272 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3273 		    pf_cksum_fixup(pf_cksum_fixup(*ic,
3274 		    oia.addr16[0], ia->addr16[0], u),
3275 		    oia.addr16[1], ia->addr16[1], u),
3276 		    oia.addr16[2], ia->addr16[2], u),
3277 		    oia.addr16[3], ia->addr16[3], u),
3278 		    oia.addr16[4], ia->addr16[4], u),
3279 		    oia.addr16[5], ia->addr16[5], u),
3280 		    oia.addr16[6], ia->addr16[6], u),
3281 		    oia.addr16[7], ia->addr16[7], u);
3282 		break;
3283 #endif /* INET6 */
3284 	}
3285 	/* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
3286 	if (oa) {
3287 		PF_ACPY(oa, na, af);
3288 		switch (af) {
3289 #ifdef INET
3290 		case AF_INET:
3291 			*hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
3292 			    ooa.addr16[0], oa->addr16[0], 0),
3293 			    ooa.addr16[1], oa->addr16[1], 0);
3294 			break;
3295 #endif /* INET */
3296 #ifdef INET6
3297 		case AF_INET6:
3298 			*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3299 			    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3300 			    pf_cksum_fixup(pf_cksum_fixup(*ic,
3301 			    ooa.addr16[0], oa->addr16[0], u),
3302 			    ooa.addr16[1], oa->addr16[1], u),
3303 			    ooa.addr16[2], oa->addr16[2], u),
3304 			    ooa.addr16[3], oa->addr16[3], u),
3305 			    ooa.addr16[4], oa->addr16[4], u),
3306 			    ooa.addr16[5], oa->addr16[5], u),
3307 			    ooa.addr16[6], oa->addr16[6], u),
3308 			    ooa.addr16[7], oa->addr16[7], u);
3309 			break;
3310 #endif /* INET6 */
3311 		}
3312 	}
3313 }
3314 
3315 /*
3316  * Need to modulate the sequence numbers in the TCP SACK option
3317  * (credits to Krzysztof Pfaff for report and patch)
3318  */
3319 static int
pf_modulate_sack(struct pf_pdesc * pd,struct tcphdr * th,struct pf_state_peer * dst)3320 pf_modulate_sack(struct pf_pdesc *pd, struct tcphdr *th,
3321     struct pf_state_peer *dst)
3322 {
3323 	int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
3324 	u_int8_t opts[TCP_MAXOLEN], *opt = opts;
3325 	int copyback = 0, i, olen;
3326 	struct sackblk sack;
3327 
3328 #define	TCPOLEN_SACKLEN	(TCPOLEN_SACK + 2)
3329 	if (hlen < TCPOLEN_SACKLEN ||
3330 	    !pf_pull_hdr(pd->m, pd->off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
3331 		return 0;
3332 
3333 	while (hlen >= TCPOLEN_SACKLEN) {
3334 		size_t startoff = opt - opts;
3335 		olen = opt[1];
3336 		switch (*opt) {
3337 		case TCPOPT_EOL:	/* FALLTHROUGH */
3338 		case TCPOPT_NOP:
3339 			opt++;
3340 			hlen--;
3341 			break;
3342 		case TCPOPT_SACK:
3343 			if (olen > hlen)
3344 				olen = hlen;
3345 			if (olen >= TCPOLEN_SACKLEN) {
3346 				for (i = 2; i + TCPOLEN_SACK <= olen;
3347 				    i += TCPOLEN_SACK) {
3348 					memcpy(&sack, &opt[i], sizeof(sack));
3349 					pf_patch_32_unaligned(pd->m,
3350 					    &th->th_sum, &sack.start,
3351 					    htonl(ntohl(sack.start) - dst->seqdiff),
3352 					    PF_ALGNMNT(startoff),
3353 					    0);
3354 					pf_patch_32_unaligned(pd->m, &th->th_sum,
3355 					    &sack.end,
3356 					    htonl(ntohl(sack.end) - dst->seqdiff),
3357 					    PF_ALGNMNT(startoff),
3358 					    0);
3359 					memcpy(&opt[i], &sack, sizeof(sack));
3360 				}
3361 				copyback = 1;
3362 			}
3363 			/* FALLTHROUGH */
3364 		default:
3365 			if (olen < 2)
3366 				olen = 2;
3367 			hlen -= olen;
3368 			opt += olen;
3369 		}
3370 	}
3371 
3372 	if (copyback)
3373 		m_copyback(pd->m, pd->off + sizeof(*th), thoptlen, (caddr_t)opts);
3374 	return (copyback);
3375 }
3376 
3377 struct mbuf *
pf_build_tcp(const struct pf_krule * r,sa_family_t af,const struct pf_addr * saddr,const struct pf_addr * daddr,u_int16_t sport,u_int16_t dport,u_int32_t seq,u_int32_t ack,u_int8_t tcp_flags,u_int16_t win,u_int16_t mss,u_int8_t ttl,int mbuf_flags,u_int16_t mtag_tag,u_int16_t mtag_flags,int rtableid)3378 pf_build_tcp(const struct pf_krule *r, sa_family_t af,
3379     const struct pf_addr *saddr, const struct pf_addr *daddr,
3380     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
3381     u_int8_t tcp_flags, u_int16_t win, u_int16_t mss, u_int8_t ttl,
3382     int mbuf_flags, u_int16_t mtag_tag, u_int16_t mtag_flags, int rtableid)
3383 {
3384 	struct mbuf	*m;
3385 	int		 len, tlen;
3386 #ifdef INET
3387 	struct ip	*h = NULL;
3388 #endif /* INET */
3389 #ifdef INET6
3390 	struct ip6_hdr	*h6 = NULL;
3391 #endif /* INET6 */
3392 	struct tcphdr	*th;
3393 	char		*opt;
3394 	struct pf_mtag  *pf_mtag;
3395 
3396 	len = 0;
3397 	th = NULL;
3398 
3399 	/* maximum segment size tcp option */
3400 	tlen = sizeof(struct tcphdr);
3401 	if (mss)
3402 		tlen += 4;
3403 
3404 	switch (af) {
3405 #ifdef INET
3406 	case AF_INET:
3407 		len = sizeof(struct ip) + tlen;
3408 		break;
3409 #endif /* INET */
3410 #ifdef INET6
3411 	case AF_INET6:
3412 		len = sizeof(struct ip6_hdr) + tlen;
3413 		break;
3414 #endif /* INET6 */
3415 	}
3416 
3417 	m = m_gethdr(M_NOWAIT, MT_DATA);
3418 	if (m == NULL)
3419 		return (NULL);
3420 
3421 #ifdef MAC
3422 	mac_netinet_firewall_send(m);
3423 #endif
3424 	if ((pf_mtag = pf_get_mtag(m)) == NULL) {
3425 		m_freem(m);
3426 		return (NULL);
3427 	}
3428 	m->m_flags |= mbuf_flags;
3429 	pf_mtag->tag = mtag_tag;
3430 	pf_mtag->flags = mtag_flags;
3431 
3432 	if (rtableid >= 0)
3433 		M_SETFIB(m, rtableid);
3434 
3435 #ifdef ALTQ
3436 	if (r != NULL && r->qid) {
3437 		pf_mtag->qid = r->qid;
3438 
3439 		/* add hints for ecn */
3440 		pf_mtag->hdr = mtod(m, struct ip *);
3441 	}
3442 #endif /* ALTQ */
3443 	m->m_data += max_linkhdr;
3444 	m->m_pkthdr.len = m->m_len = len;
3445 	/* The rest of the stack assumes a rcvif, so provide one.
3446 	 * This is a locally generated packet, so .. close enough. */
3447 	m->m_pkthdr.rcvif = V_loif;
3448 	bzero(m->m_data, len);
3449 	switch (af) {
3450 #ifdef INET
3451 	case AF_INET:
3452 		h = mtod(m, struct ip *);
3453 
3454 		/* IP header fields included in the TCP checksum */
3455 		h->ip_p = IPPROTO_TCP;
3456 		h->ip_len = htons(tlen);
3457 		h->ip_src.s_addr = saddr->v4.s_addr;
3458 		h->ip_dst.s_addr = daddr->v4.s_addr;
3459 
3460 		th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
3461 		break;
3462 #endif /* INET */
3463 #ifdef INET6
3464 	case AF_INET6:
3465 		h6 = mtod(m, struct ip6_hdr *);
3466 
3467 		/* IP header fields included in the TCP checksum */
3468 		h6->ip6_nxt = IPPROTO_TCP;
3469 		h6->ip6_plen = htons(tlen);
3470 		memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
3471 		memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
3472 
3473 		th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
3474 		break;
3475 #endif /* INET6 */
3476 	}
3477 
3478 	/* TCP header */
3479 	th->th_sport = sport;
3480 	th->th_dport = dport;
3481 	th->th_seq = htonl(seq);
3482 	th->th_ack = htonl(ack);
3483 	th->th_off = tlen >> 2;
3484 	tcp_set_flags(th, tcp_flags);
3485 	th->th_win = htons(win);
3486 
3487 	if (mss) {
3488 		opt = (char *)(th + 1);
3489 		opt[0] = TCPOPT_MAXSEG;
3490 		opt[1] = 4;
3491 		HTONS(mss);
3492 		bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
3493 	}
3494 
3495 	switch (af) {
3496 #ifdef INET
3497 	case AF_INET:
3498 		/* TCP checksum */
3499 		th->th_sum = in_cksum(m, len);
3500 
3501 		/* Finish the IP header */
3502 		h->ip_v = 4;
3503 		h->ip_hl = sizeof(*h) >> 2;
3504 		h->ip_tos = IPTOS_LOWDELAY;
3505 		h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
3506 		h->ip_len = htons(len);
3507 		h->ip_ttl = ttl ? ttl : V_ip_defttl;
3508 		h->ip_sum = 0;
3509 		break;
3510 #endif /* INET */
3511 #ifdef INET6
3512 	case AF_INET6:
3513 		/* TCP checksum */
3514 		th->th_sum = in6_cksum(m, IPPROTO_TCP,
3515 		    sizeof(struct ip6_hdr), tlen);
3516 
3517 		h6->ip6_vfc |= IPV6_VERSION;
3518 		h6->ip6_hlim = IPV6_DEFHLIM;
3519 		break;
3520 #endif /* INET6 */
3521 	}
3522 
3523 	return (m);
3524 }
3525 
3526 static void
pf_send_sctp_abort(sa_family_t af,struct pf_pdesc * pd,uint8_t ttl,int rtableid)3527 pf_send_sctp_abort(sa_family_t af, struct pf_pdesc *pd,
3528     uint8_t ttl, int rtableid)
3529 {
3530 	struct mbuf		*m;
3531 #ifdef INET
3532 	struct ip		*h = NULL;
3533 #endif /* INET */
3534 #ifdef INET6
3535 	struct ip6_hdr		*h6 = NULL;
3536 #endif /* INET6 */
3537 	struct sctphdr		*hdr;
3538 	struct sctp_chunkhdr	*chunk;
3539 	struct pf_send_entry	*pfse;
3540 	int			 off = 0;
3541 
3542 	MPASS(af == pd->af);
3543 
3544 	m = m_gethdr(M_NOWAIT, MT_DATA);
3545 	if (m == NULL)
3546 		return;
3547 
3548 	m->m_data += max_linkhdr;
3549 	m->m_flags |= M_SKIP_FIREWALL;
3550 	/* The rest of the stack assumes a rcvif, so provide one.
3551 	 * This is a locally generated packet, so .. close enough. */
3552 	m->m_pkthdr.rcvif = V_loif;
3553 
3554 	/* IPv4|6 header */
3555 	switch (af) {
3556 #ifdef INET
3557 	case AF_INET:
3558 		bzero(m->m_data, sizeof(struct ip) + sizeof(*hdr) + sizeof(*chunk));
3559 
3560 		h = mtod(m, struct ip *);
3561 
3562 		/* IP header fields included in the TCP checksum */
3563 
3564 		h->ip_p = IPPROTO_SCTP;
3565 		h->ip_len = htons(sizeof(*h) + sizeof(*hdr) + sizeof(*chunk));
3566 		h->ip_ttl = ttl ? ttl : V_ip_defttl;
3567 		h->ip_src = pd->dst->v4;
3568 		h->ip_dst = pd->src->v4;
3569 
3570 		off += sizeof(struct ip);
3571 		break;
3572 #endif /* INET */
3573 #ifdef INET6
3574 	case AF_INET6:
3575 		bzero(m->m_data, sizeof(struct ip6_hdr) + sizeof(*hdr) + sizeof(*chunk));
3576 
3577 		h6 = mtod(m, struct ip6_hdr *);
3578 
3579 		/* IP header fields included in the TCP checksum */
3580 		h6->ip6_vfc |= IPV6_VERSION;
3581 		h6->ip6_nxt = IPPROTO_SCTP;
3582 		h6->ip6_plen = htons(sizeof(*h6) + sizeof(*hdr) + sizeof(*chunk));
3583 		h6->ip6_hlim = ttl ? ttl : V_ip6_defhlim;
3584 		memcpy(&h6->ip6_src, &pd->dst->v6, sizeof(struct in6_addr));
3585 		memcpy(&h6->ip6_dst, &pd->src->v6, sizeof(struct in6_addr));
3586 
3587 		off += sizeof(struct ip6_hdr);
3588 		break;
3589 #endif /* INET6 */
3590 	}
3591 
3592 	/* SCTP header */
3593 	hdr = mtodo(m, off);
3594 
3595 	hdr->src_port = pd->hdr.sctp.dest_port;
3596 	hdr->dest_port = pd->hdr.sctp.src_port;
3597 	hdr->v_tag = pd->sctp_initiate_tag;
3598 	hdr->checksum = 0;
3599 
3600 	/* Abort chunk. */
3601 	off += sizeof(struct sctphdr);
3602 	chunk = mtodo(m, off);
3603 
3604 	chunk->chunk_type = SCTP_ABORT_ASSOCIATION;
3605 	chunk->chunk_length = htons(sizeof(*chunk));
3606 
3607 	/* SCTP checksum */
3608 	off += sizeof(*chunk);
3609 	m->m_pkthdr.len = m->m_len = off;
3610 
3611 	pf_sctp_checksum(m, off - sizeof(*hdr) - sizeof(*chunk));
3612 
3613 	if (rtableid >= 0)
3614 		M_SETFIB(m, rtableid);
3615 
3616 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3617 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3618 	if (pfse == NULL) {
3619 		m_freem(m);
3620 		return;
3621 	}
3622 
3623 	switch (af) {
3624 #ifdef INET
3625 	case AF_INET:
3626 		pfse->pfse_type = PFSE_IP;
3627 		break;
3628 #endif /* INET */
3629 #ifdef INET6
3630 	case AF_INET6:
3631 		pfse->pfse_type = PFSE_IP6;
3632 		break;
3633 #endif /* INET6 */
3634 	}
3635 
3636 	pfse->pfse_m = m;
3637 	pf_send(pfse);
3638 }
3639 
3640 void
pf_send_tcp(const struct pf_krule * r,sa_family_t af,const struct pf_addr * saddr,const struct pf_addr * daddr,u_int16_t sport,u_int16_t dport,u_int32_t seq,u_int32_t ack,u_int8_t tcp_flags,u_int16_t win,u_int16_t mss,u_int8_t ttl,int mbuf_flags,u_int16_t mtag_tag,u_int16_t mtag_flags,int rtableid)3641 pf_send_tcp(const struct pf_krule *r, sa_family_t af,
3642     const struct pf_addr *saddr, const struct pf_addr *daddr,
3643     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
3644     u_int8_t tcp_flags, u_int16_t win, u_int16_t mss, u_int8_t ttl,
3645     int mbuf_flags, u_int16_t mtag_tag, u_int16_t mtag_flags, int rtableid)
3646 {
3647 	struct pf_send_entry *pfse;
3648 	struct mbuf	*m;
3649 
3650 	m = pf_build_tcp(r, af, saddr, daddr, sport, dport, seq, ack, tcp_flags,
3651 	    win, mss, ttl, mbuf_flags, mtag_tag, mtag_flags, rtableid);
3652 	if (m == NULL)
3653 		return;
3654 
3655 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3656 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3657 	if (pfse == NULL) {
3658 		m_freem(m);
3659 		return;
3660 	}
3661 
3662 	switch (af) {
3663 #ifdef INET
3664 	case AF_INET:
3665 		pfse->pfse_type = PFSE_IP;
3666 		break;
3667 #endif /* INET */
3668 #ifdef INET6
3669 	case AF_INET6:
3670 		pfse->pfse_type = PFSE_IP6;
3671 		break;
3672 #endif /* INET6 */
3673 	}
3674 
3675 	pfse->pfse_m = m;
3676 	pf_send(pfse);
3677 }
3678 
3679 static void
pf_return(struct pf_krule * r,struct pf_krule * nr,struct pf_pdesc * pd,struct pf_state_key * sk,struct tcphdr * th,u_int16_t bproto_sum,u_int16_t bip_sum,u_short * reason,int rtableid)3680 pf_return(struct pf_krule *r, struct pf_krule *nr, struct pf_pdesc *pd,
3681     struct pf_state_key *sk, struct tcphdr *th,
3682     u_int16_t bproto_sum, u_int16_t bip_sum,
3683     u_short *reason, int rtableid)
3684 {
3685 	struct pf_addr	* const saddr = pd->src;
3686 	struct pf_addr	* const daddr = pd->dst;
3687 
3688 	/* undo NAT changes, if they have taken place */
3689 	if (nr != NULL) {
3690 		PF_ACPY(saddr, &sk->addr[pd->sidx], pd->af);
3691 		PF_ACPY(daddr, &sk->addr[pd->didx], pd->af);
3692 		if (pd->sport)
3693 			*pd->sport = sk->port[pd->sidx];
3694 		if (pd->dport)
3695 			*pd->dport = sk->port[pd->didx];
3696 		if (pd->proto_sum)
3697 			*pd->proto_sum = bproto_sum;
3698 		if (pd->ip_sum)
3699 			*pd->ip_sum = bip_sum;
3700 		m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
3701 	}
3702 	if (pd->proto == IPPROTO_TCP &&
3703 	    ((r->rule_flag & PFRULE_RETURNRST) ||
3704 	    (r->rule_flag & PFRULE_RETURN)) &&
3705 	    !(tcp_get_flags(th) & TH_RST)) {
3706 		u_int32_t	 ack = ntohl(th->th_seq) + pd->p_len;
3707 
3708 		if (pf_check_proto_cksum(pd->m, pd->off, pd->tot_len - pd->off,
3709 		    IPPROTO_TCP, pd->af))
3710 			REASON_SET(reason, PFRES_PROTCKSUM);
3711 		else {
3712 			if (tcp_get_flags(th) & TH_SYN)
3713 				ack++;
3714 			if (tcp_get_flags(th) & TH_FIN)
3715 				ack++;
3716 			pf_send_tcp(r, pd->af, pd->dst,
3717 				pd->src, th->th_dport, th->th_sport,
3718 				ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3719 				r->return_ttl, M_SKIP_FIREWALL, 0, 0, rtableid);
3720 		}
3721 	} else if (pd->proto == IPPROTO_SCTP &&
3722 	    (r->rule_flag & PFRULE_RETURN)) {
3723 		pf_send_sctp_abort(pd->af, pd, r->return_ttl, rtableid);
3724 	} else if (pd->proto != IPPROTO_ICMP && pd->af == AF_INET &&
3725 		r->return_icmp)
3726 		pf_send_icmp(pd->m, r->return_icmp >> 8,
3727 			r->return_icmp & 255, pd->af, r, rtableid);
3728 	else if (pd->proto != IPPROTO_ICMPV6 && pd->af == AF_INET6 &&
3729 		r->return_icmp6)
3730 		pf_send_icmp(pd->m, r->return_icmp6 >> 8,
3731 			r->return_icmp6 & 255, pd->af, r, rtableid);
3732 }
3733 
3734 static int
pf_match_ieee8021q_pcp(u_int8_t prio,struct mbuf * m)3735 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
3736 {
3737 	struct m_tag *mtag;
3738 	u_int8_t mpcp;
3739 
3740 	mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
3741 	if (mtag == NULL)
3742 		return (0);
3743 
3744 	if (prio == PF_PRIO_ZERO)
3745 		prio = 0;
3746 
3747 	mpcp = *(uint8_t *)(mtag + 1);
3748 
3749 	return (mpcp == prio);
3750 }
3751 
3752 static int
pf_icmp_to_bandlim(uint8_t type)3753 pf_icmp_to_bandlim(uint8_t type)
3754 {
3755 	switch (type) {
3756 		case ICMP_ECHO:
3757 		case ICMP_ECHOREPLY:
3758 			return (BANDLIM_ICMP_ECHO);
3759 		case ICMP_TSTAMP:
3760 		case ICMP_TSTAMPREPLY:
3761 			return (BANDLIM_ICMP_TSTAMP);
3762 		case ICMP_UNREACH:
3763 		default:
3764 			return (BANDLIM_ICMP_UNREACH);
3765 	}
3766 }
3767 
3768 static void
pf_send_icmp(struct mbuf * m,u_int8_t type,u_int8_t code,sa_family_t af,struct pf_krule * r,int rtableid)3769 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
3770     struct pf_krule *r, int rtableid)
3771 {
3772 	struct pf_send_entry *pfse;
3773 	struct mbuf *m0;
3774 	struct pf_mtag *pf_mtag;
3775 
3776 	/* ICMP packet rate limitation. */
3777 	switch (af) {
3778 #ifdef INET6
3779 	case AF_INET6:
3780 		if (icmp6_ratelimit(NULL, type, code))
3781 			return;
3782 		break;
3783 #endif
3784 #ifdef INET
3785 	case AF_INET:
3786 		if (badport_bandlim(pf_icmp_to_bandlim(type)) != 0)
3787 			return;
3788 		break;
3789 #endif
3790 	}
3791 
3792 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3793 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3794 	if (pfse == NULL)
3795 		return;
3796 
3797 	if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
3798 		free(pfse, M_PFTEMP);
3799 		return;
3800 	}
3801 
3802 	if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
3803 		free(pfse, M_PFTEMP);
3804 		return;
3805 	}
3806 	/* XXX: revisit */
3807 	m0->m_flags |= M_SKIP_FIREWALL;
3808 
3809 	if (rtableid >= 0)
3810 		M_SETFIB(m0, rtableid);
3811 
3812 #ifdef ALTQ
3813 	if (r->qid) {
3814 		pf_mtag->qid = r->qid;
3815 		/* add hints for ecn */
3816 		pf_mtag->hdr = mtod(m0, struct ip *);
3817 	}
3818 #endif /* ALTQ */
3819 
3820 	switch (af) {
3821 #ifdef INET
3822 	case AF_INET:
3823 		pfse->pfse_type = PFSE_ICMP;
3824 		break;
3825 #endif /* INET */
3826 #ifdef INET6
3827 	case AF_INET6:
3828 		pfse->pfse_type = PFSE_ICMP6;
3829 		break;
3830 #endif /* INET6 */
3831 	}
3832 	pfse->pfse_m = m0;
3833 	pfse->icmpopts.type = type;
3834 	pfse->icmpopts.code = code;
3835 	pf_send(pfse);
3836 }
3837 
3838 /*
3839  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
3840  * If n is 0, they match if they are equal. If n is != 0, they match if they
3841  * are different.
3842  */
3843 int
pf_match_addr(u_int8_t n,struct pf_addr * a,struct pf_addr * m,struct pf_addr * b,sa_family_t af)3844 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
3845     struct pf_addr *b, sa_family_t af)
3846 {
3847 	int	match = 0;
3848 
3849 	switch (af) {
3850 #ifdef INET
3851 	case AF_INET:
3852 		if (IN_ARE_MASKED_ADDR_EQUAL(a->v4, b->v4, m->v4))
3853 			match++;
3854 		break;
3855 #endif /* INET */
3856 #ifdef INET6
3857 	case AF_INET6:
3858 		if (IN6_ARE_MASKED_ADDR_EQUAL(&a->v6, &b->v6, &m->v6))
3859 			match++;
3860 		break;
3861 #endif /* INET6 */
3862 	}
3863 	if (match) {
3864 		if (n)
3865 			return (0);
3866 		else
3867 			return (1);
3868 	} else {
3869 		if (n)
3870 			return (1);
3871 		else
3872 			return (0);
3873 	}
3874 }
3875 
3876 /*
3877  * Return 1 if b <= a <= e, otherwise return 0.
3878  */
3879 int
pf_match_addr_range(struct pf_addr * b,struct pf_addr * e,struct pf_addr * a,sa_family_t af)3880 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
3881     struct pf_addr *a, sa_family_t af)
3882 {
3883 	switch (af) {
3884 #ifdef INET
3885 	case AF_INET:
3886 		if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
3887 		    (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
3888 			return (0);
3889 		break;
3890 #endif /* INET */
3891 #ifdef INET6
3892 	case AF_INET6: {
3893 		int	i;
3894 
3895 		/* check a >= b */
3896 		for (i = 0; i < 4; ++i)
3897 			if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
3898 				break;
3899 			else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
3900 				return (0);
3901 		/* check a <= e */
3902 		for (i = 0; i < 4; ++i)
3903 			if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
3904 				break;
3905 			else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
3906 				return (0);
3907 		break;
3908 	}
3909 #endif /* INET6 */
3910 	}
3911 	return (1);
3912 }
3913 
3914 static int
pf_match(u_int8_t op,u_int32_t a1,u_int32_t a2,u_int32_t p)3915 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
3916 {
3917 	switch (op) {
3918 	case PF_OP_IRG:
3919 		return ((p > a1) && (p < a2));
3920 	case PF_OP_XRG:
3921 		return ((p < a1) || (p > a2));
3922 	case PF_OP_RRG:
3923 		return ((p >= a1) && (p <= a2));
3924 	case PF_OP_EQ:
3925 		return (p == a1);
3926 	case PF_OP_NE:
3927 		return (p != a1);
3928 	case PF_OP_LT:
3929 		return (p < a1);
3930 	case PF_OP_LE:
3931 		return (p <= a1);
3932 	case PF_OP_GT:
3933 		return (p > a1);
3934 	case PF_OP_GE:
3935 		return (p >= a1);
3936 	}
3937 	return (0); /* never reached */
3938 }
3939 
3940 int
pf_match_port(u_int8_t op,u_int16_t a1,u_int16_t a2,u_int16_t p)3941 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
3942 {
3943 	NTOHS(a1);
3944 	NTOHS(a2);
3945 	NTOHS(p);
3946 	return (pf_match(op, a1, a2, p));
3947 }
3948 
3949 static int
pf_match_uid(u_int8_t op,uid_t a1,uid_t a2,uid_t u)3950 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
3951 {
3952 	if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3953 		return (0);
3954 	return (pf_match(op, a1, a2, u));
3955 }
3956 
3957 static int
pf_match_gid(u_int8_t op,gid_t a1,gid_t a2,gid_t g)3958 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
3959 {
3960 	if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3961 		return (0);
3962 	return (pf_match(op, a1, a2, g));
3963 }
3964 
3965 int
pf_match_tag(struct mbuf * m,struct pf_krule * r,int * tag,int mtag)3966 pf_match_tag(struct mbuf *m, struct pf_krule *r, int *tag, int mtag)
3967 {
3968 	if (*tag == -1)
3969 		*tag = mtag;
3970 
3971 	return ((!r->match_tag_not && r->match_tag == *tag) ||
3972 	    (r->match_tag_not && r->match_tag != *tag));
3973 }
3974 
3975 static int
pf_match_rcvif(struct mbuf * m,struct pf_krule * r)3976 pf_match_rcvif(struct mbuf *m, struct pf_krule *r)
3977 {
3978 	struct ifnet *ifp = m->m_pkthdr.rcvif;
3979 	struct pfi_kkif *kif;
3980 
3981 	if (ifp == NULL)
3982 		return (0);
3983 
3984 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
3985 
3986 	if (kif == NULL) {
3987 		DPFPRINTF(PF_DEBUG_URGENT,
3988 		    ("pf_test_via: kif == NULL, @%d via %s\n", r->nr,
3989 			r->rcv_ifname));
3990 		return (0);
3991 	}
3992 
3993 	return (pfi_kkif_match(r->rcv_kif, kif));
3994 }
3995 
3996 int
pf_tag_packet(struct pf_pdesc * pd,int tag)3997 pf_tag_packet(struct pf_pdesc *pd, int tag)
3998 {
3999 
4000 	KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
4001 
4002 	if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(pd->m)) == NULL))
4003 		return (ENOMEM);
4004 
4005 	pd->pf_mtag->tag = tag;
4006 
4007 	return (0);
4008 }
4009 
4010 #define	PF_ANCHOR_STACKSIZE	32
4011 struct pf_kanchor_stackframe {
4012 	struct pf_kruleset	*rs;
4013 	struct pf_krule		*r;	/* XXX: + match bit */
4014 	struct pf_kanchor	*child;
4015 };
4016 
4017 /*
4018  * XXX: We rely on malloc(9) returning pointer aligned addresses.
4019  */
4020 #define	PF_ANCHORSTACK_MATCH	0x00000001
4021 #define	PF_ANCHORSTACK_MASK	(PF_ANCHORSTACK_MATCH)
4022 
4023 #define	PF_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
4024 #define	PF_ANCHOR_RULE(f)	(struct pf_krule *)			\
4025 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
4026 #define	PF_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 			\
4027 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
4028 } while (0)
4029 
4030 void
pf_step_into_anchor(struct pf_kanchor_stackframe * stack,int * depth,struct pf_kruleset ** rs,int n,struct pf_krule ** r,struct pf_krule ** a,int * match)4031 pf_step_into_anchor(struct pf_kanchor_stackframe *stack, int *depth,
4032     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
4033     int *match)
4034 {
4035 	struct pf_kanchor_stackframe	*f;
4036 
4037 	PF_RULES_RASSERT();
4038 
4039 	if (match)
4040 		*match = 0;
4041 	if (*depth >= PF_ANCHOR_STACKSIZE) {
4042 		printf("%s: anchor stack overflow on %s\n",
4043 		    __func__, (*r)->anchor->name);
4044 		*r = TAILQ_NEXT(*r, entries);
4045 		return;
4046 	} else if (*depth == 0 && a != NULL)
4047 		*a = *r;
4048 	f = stack + (*depth)++;
4049 	f->rs = *rs;
4050 	f->r = *r;
4051 	if ((*r)->anchor_wildcard) {
4052 		struct pf_kanchor_node *parent = &(*r)->anchor->children;
4053 
4054 		if ((f->child = RB_MIN(pf_kanchor_node, parent)) == NULL) {
4055 			*r = NULL;
4056 			return;
4057 		}
4058 		*rs = &f->child->ruleset;
4059 	} else {
4060 		f->child = NULL;
4061 		*rs = &(*r)->anchor->ruleset;
4062 	}
4063 	*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
4064 }
4065 
4066 int
pf_step_out_of_anchor(struct pf_kanchor_stackframe * stack,int * depth,struct pf_kruleset ** rs,int n,struct pf_krule ** r,struct pf_krule ** a,int * match)4067 pf_step_out_of_anchor(struct pf_kanchor_stackframe *stack, int *depth,
4068     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
4069     int *match)
4070 {
4071 	struct pf_kanchor_stackframe	*f;
4072 	struct pf_krule *fr;
4073 	int quick = 0;
4074 
4075 	PF_RULES_RASSERT();
4076 
4077 	do {
4078 		if (*depth <= 0)
4079 			break;
4080 		f = stack + *depth - 1;
4081 		fr = PF_ANCHOR_RULE(f);
4082 		if (f->child != NULL) {
4083 			/*
4084 			 * This block traverses through
4085 			 * a wildcard anchor.
4086 			 */
4087 			if (match != NULL && *match) {
4088 				/*
4089 				 * If any of "*" matched, then
4090 				 * "foo/ *" matched, mark frame
4091 				 * appropriately.
4092 				 */
4093 				PF_ANCHOR_SET_MATCH(f);
4094 				*match = 0;
4095 			}
4096 			f->child = RB_NEXT(pf_kanchor_node,
4097 			    &fr->anchor->children, f->child);
4098 			if (f->child != NULL) {
4099 				*rs = &f->child->ruleset;
4100 				*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
4101 				if (*r == NULL)
4102 					continue;
4103 				else
4104 					break;
4105 			}
4106 		}
4107 		(*depth)--;
4108 		if (*depth == 0 && a != NULL)
4109 			*a = NULL;
4110 		*rs = f->rs;
4111 		if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
4112 			quick = fr->quick;
4113 		*r = TAILQ_NEXT(fr, entries);
4114 	} while (*r == NULL);
4115 
4116 	return (quick);
4117 }
4118 
4119 struct pf_keth_anchor_stackframe {
4120 	struct pf_keth_ruleset	*rs;
4121 	struct pf_keth_rule	*r;	/* XXX: + match bit */
4122 	struct pf_keth_anchor	*child;
4123 };
4124 
4125 #define	PF_ETH_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
4126 #define	PF_ETH_ANCHOR_RULE(f)	(struct pf_keth_rule *)			\
4127 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
4128 #define	PF_ETH_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 		\
4129 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
4130 } while (0)
4131 
4132 void
pf_step_into_keth_anchor(struct pf_keth_anchor_stackframe * stack,int * depth,struct pf_keth_ruleset ** rs,struct pf_keth_rule ** r,struct pf_keth_rule ** a,int * match)4133 pf_step_into_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
4134     struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
4135     struct pf_keth_rule **a, int *match)
4136 {
4137 	struct pf_keth_anchor_stackframe	*f;
4138 
4139 	NET_EPOCH_ASSERT();
4140 
4141 	if (match)
4142 		*match = 0;
4143 	if (*depth >= PF_ANCHOR_STACKSIZE) {
4144 		printf("%s: anchor stack overflow on %s\n",
4145 		    __func__, (*r)->anchor->name);
4146 		*r = TAILQ_NEXT(*r, entries);
4147 		return;
4148 	} else if (*depth == 0 && a != NULL)
4149 		*a = *r;
4150 	f = stack + (*depth)++;
4151 	f->rs = *rs;
4152 	f->r = *r;
4153 	if ((*r)->anchor_wildcard) {
4154 		struct pf_keth_anchor_node *parent = &(*r)->anchor->children;
4155 
4156 		if ((f->child = RB_MIN(pf_keth_anchor_node, parent)) == NULL) {
4157 			*r = NULL;
4158 			return;
4159 		}
4160 		*rs = &f->child->ruleset;
4161 	} else {
4162 		f->child = NULL;
4163 		*rs = &(*r)->anchor->ruleset;
4164 	}
4165 	*r = TAILQ_FIRST((*rs)->active.rules);
4166 }
4167 
4168 int
pf_step_out_of_keth_anchor(struct pf_keth_anchor_stackframe * stack,int * depth,struct pf_keth_ruleset ** rs,struct pf_keth_rule ** r,struct pf_keth_rule ** a,int * match)4169 pf_step_out_of_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
4170     struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
4171     struct pf_keth_rule **a, int *match)
4172 {
4173 	struct pf_keth_anchor_stackframe	*f;
4174 	struct pf_keth_rule *fr;
4175 	int quick = 0;
4176 
4177 	NET_EPOCH_ASSERT();
4178 
4179 	do {
4180 		if (*depth <= 0)
4181 			break;
4182 		f = stack + *depth - 1;
4183 		fr = PF_ETH_ANCHOR_RULE(f);
4184 		if (f->child != NULL) {
4185 			/*
4186 			 * This block traverses through
4187 			 * a wildcard anchor.
4188 			 */
4189 			if (match != NULL && *match) {
4190 				/*
4191 				 * If any of "*" matched, then
4192 				 * "foo/ *" matched, mark frame
4193 				 * appropriately.
4194 				 */
4195 				PF_ETH_ANCHOR_SET_MATCH(f);
4196 				*match = 0;
4197 			}
4198 			f->child = RB_NEXT(pf_keth_anchor_node,
4199 			    &fr->anchor->children, f->child);
4200 			if (f->child != NULL) {
4201 				*rs = &f->child->ruleset;
4202 				*r = TAILQ_FIRST((*rs)->active.rules);
4203 				if (*r == NULL)
4204 					continue;
4205 				else
4206 					break;
4207 			}
4208 		}
4209 		(*depth)--;
4210 		if (*depth == 0 && a != NULL)
4211 			*a = NULL;
4212 		*rs = f->rs;
4213 		if (PF_ETH_ANCHOR_MATCH(f) || (match != NULL && *match))
4214 			quick = fr->quick;
4215 		*r = TAILQ_NEXT(fr, entries);
4216 	} while (*r == NULL);
4217 
4218 	return (quick);
4219 }
4220 
4221 #ifdef INET6
4222 void
pf_poolmask(struct pf_addr * naddr,struct pf_addr * raddr,struct pf_addr * rmask,struct pf_addr * saddr,sa_family_t af)4223 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
4224     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
4225 {
4226 	switch (af) {
4227 #ifdef INET
4228 	case AF_INET:
4229 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
4230 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
4231 		break;
4232 #endif /* INET */
4233 	case AF_INET6:
4234 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
4235 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
4236 		naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
4237 		((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
4238 		naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
4239 		((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
4240 		naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
4241 		((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
4242 		break;
4243 	}
4244 }
4245 
4246 void
pf_addr_inc(struct pf_addr * addr,sa_family_t af)4247 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
4248 {
4249 	switch (af) {
4250 #ifdef INET
4251 	case AF_INET:
4252 		addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
4253 		break;
4254 #endif /* INET */
4255 	case AF_INET6:
4256 		if (addr->addr32[3] == 0xffffffff) {
4257 			addr->addr32[3] = 0;
4258 			if (addr->addr32[2] == 0xffffffff) {
4259 				addr->addr32[2] = 0;
4260 				if (addr->addr32[1] == 0xffffffff) {
4261 					addr->addr32[1] = 0;
4262 					addr->addr32[0] =
4263 					    htonl(ntohl(addr->addr32[0]) + 1);
4264 				} else
4265 					addr->addr32[1] =
4266 					    htonl(ntohl(addr->addr32[1]) + 1);
4267 			} else
4268 				addr->addr32[2] =
4269 				    htonl(ntohl(addr->addr32[2]) + 1);
4270 		} else
4271 			addr->addr32[3] =
4272 			    htonl(ntohl(addr->addr32[3]) + 1);
4273 		break;
4274 	}
4275 }
4276 #endif /* INET6 */
4277 
4278 void
pf_rule_to_actions(struct pf_krule * r,struct pf_rule_actions * a)4279 pf_rule_to_actions(struct pf_krule *r, struct pf_rule_actions *a)
4280 {
4281 	/*
4282 	 * Modern rules use the same flags in rules as they do in states.
4283 	 */
4284 	a->flags |= (r->scrub_flags & (PFSTATE_NODF|PFSTATE_RANDOMID|
4285 	    PFSTATE_SCRUB_TCP|PFSTATE_SETPRIO));
4286 
4287 	/*
4288 	 * Old-style scrub rules have different flags which need to be translated.
4289 	 */
4290 	if (r->rule_flag & PFRULE_RANDOMID)
4291 		a->flags |= PFSTATE_RANDOMID;
4292 	if (r->scrub_flags & PFSTATE_SETTOS || r->rule_flag & PFRULE_SET_TOS ) {
4293 		a->flags |= PFSTATE_SETTOS;
4294 		a->set_tos = r->set_tos;
4295 	}
4296 
4297 	if (r->qid)
4298 		a->qid = r->qid;
4299 	if (r->pqid)
4300 		a->pqid = r->pqid;
4301 	if (r->rtableid >= 0)
4302 		a->rtableid = r->rtableid;
4303 	a->log |= r->log;
4304 	if (r->min_ttl)
4305 		a->min_ttl = r->min_ttl;
4306 	if (r->max_mss)
4307 		a->max_mss = r->max_mss;
4308 	if (r->dnpipe)
4309 		a->dnpipe = r->dnpipe;
4310 	if (r->dnrpipe)
4311 		a->dnrpipe = r->dnrpipe;
4312 	if (r->dnpipe || r->dnrpipe) {
4313 		if (r->free_flags & PFRULE_DN_IS_PIPE)
4314 			a->flags |= PFSTATE_DN_IS_PIPE;
4315 		else
4316 			a->flags &= ~PFSTATE_DN_IS_PIPE;
4317 	}
4318 	if (r->scrub_flags & PFSTATE_SETPRIO) {
4319 		a->set_prio[0] = r->set_prio[0];
4320 		a->set_prio[1] = r->set_prio[1];
4321 	}
4322 }
4323 
4324 int
pf_socket_lookup(struct pf_pdesc * pd)4325 pf_socket_lookup(struct pf_pdesc *pd)
4326 {
4327 	struct pf_addr		*saddr, *daddr;
4328 	u_int16_t		 sport, dport;
4329 	struct inpcbinfo	*pi;
4330 	struct inpcb		*inp;
4331 
4332 	pd->lookup.uid = UID_MAX;
4333 	pd->lookup.gid = GID_MAX;
4334 
4335 	switch (pd->proto) {
4336 	case IPPROTO_TCP:
4337 		sport = pd->hdr.tcp.th_sport;
4338 		dport = pd->hdr.tcp.th_dport;
4339 		pi = &V_tcbinfo;
4340 		break;
4341 	case IPPROTO_UDP:
4342 		sport = pd->hdr.udp.uh_sport;
4343 		dport = pd->hdr.udp.uh_dport;
4344 		pi = &V_udbinfo;
4345 		break;
4346 	default:
4347 		return (-1);
4348 	}
4349 	if (pd->dir == PF_IN) {
4350 		saddr = pd->src;
4351 		daddr = pd->dst;
4352 	} else {
4353 		u_int16_t	p;
4354 
4355 		p = sport;
4356 		sport = dport;
4357 		dport = p;
4358 		saddr = pd->dst;
4359 		daddr = pd->src;
4360 	}
4361 	switch (pd->af) {
4362 #ifdef INET
4363 	case AF_INET:
4364 		inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
4365 		    dport, INPLOOKUP_RLOCKPCB, NULL, pd->m);
4366 		if (inp == NULL) {
4367 			inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
4368 			   daddr->v4, dport, INPLOOKUP_WILDCARD |
4369 			   INPLOOKUP_RLOCKPCB, NULL, pd->m);
4370 			if (inp == NULL)
4371 				return (-1);
4372 		}
4373 		break;
4374 #endif /* INET */
4375 #ifdef INET6
4376 	case AF_INET6:
4377 		inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
4378 		    dport, INPLOOKUP_RLOCKPCB, NULL, pd->m);
4379 		if (inp == NULL) {
4380 			inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
4381 			    &daddr->v6, dport, INPLOOKUP_WILDCARD |
4382 			    INPLOOKUP_RLOCKPCB, NULL, pd->m);
4383 			if (inp == NULL)
4384 				return (-1);
4385 		}
4386 		break;
4387 #endif /* INET6 */
4388 	}
4389 	INP_RLOCK_ASSERT(inp);
4390 	pd->lookup.uid = inp->inp_cred->cr_uid;
4391 	pd->lookup.gid = inp->inp_cred->cr_groups[0];
4392 	INP_RUNLOCK(inp);
4393 
4394 	return (1);
4395 }
4396 
4397 u_int8_t
pf_get_wscale(struct pf_pdesc * pd)4398 pf_get_wscale(struct pf_pdesc *pd)
4399 {
4400 	struct tcphdr	*th = &pd->hdr.tcp;
4401 	int		 hlen;
4402 	u_int8_t	 hdr[60];
4403 	u_int8_t	*opt, optlen;
4404 	u_int8_t	 wscale = 0;
4405 
4406 	hlen = th->th_off << 2;		/* hlen <= sizeof(hdr) */
4407 	if (hlen <= sizeof(struct tcphdr))
4408 		return (0);
4409 	if (!pf_pull_hdr(pd->m, pd->off, hdr, hlen, NULL, NULL, pd->af))
4410 		return (0);
4411 	opt = hdr + sizeof(struct tcphdr);
4412 	hlen -= sizeof(struct tcphdr);
4413 	while (hlen >= 3) {
4414 		switch (*opt) {
4415 		case TCPOPT_EOL:
4416 		case TCPOPT_NOP:
4417 			++opt;
4418 			--hlen;
4419 			break;
4420 		case TCPOPT_WINDOW:
4421 			wscale = opt[2];
4422 			if (wscale > TCP_MAX_WINSHIFT)
4423 				wscale = TCP_MAX_WINSHIFT;
4424 			wscale |= PF_WSCALE_FLAG;
4425 			/* FALLTHROUGH */
4426 		default:
4427 			optlen = opt[1];
4428 			if (optlen < 2)
4429 				optlen = 2;
4430 			hlen -= optlen;
4431 			opt += optlen;
4432 			break;
4433 		}
4434 	}
4435 	return (wscale);
4436 }
4437 
4438 u_int16_t
pf_get_mss(struct pf_pdesc * pd)4439 pf_get_mss(struct pf_pdesc *pd)
4440 {
4441 	struct tcphdr	*th = &pd->hdr.tcp;
4442 	int		 hlen;
4443 	u_int8_t	 hdr[60];
4444 	u_int8_t	*opt, optlen;
4445 	u_int16_t	 mss = V_tcp_mssdflt;
4446 
4447 	hlen = th->th_off << 2;	/* hlen <= sizeof(hdr) */
4448 	if (hlen <= sizeof(struct tcphdr))
4449 		return (0);
4450 	if (!pf_pull_hdr(pd->m, pd->off, hdr, hlen, NULL, NULL, pd->af))
4451 		return (0);
4452 	opt = hdr + sizeof(struct tcphdr);
4453 	hlen -= sizeof(struct tcphdr);
4454 	while (hlen >= TCPOLEN_MAXSEG) {
4455 		switch (*opt) {
4456 		case TCPOPT_EOL:
4457 		case TCPOPT_NOP:
4458 			++opt;
4459 			--hlen;
4460 			break;
4461 		case TCPOPT_MAXSEG:
4462 			bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
4463 			NTOHS(mss);
4464 			/* FALLTHROUGH */
4465 		default:
4466 			optlen = opt[1];
4467 			if (optlen < 2)
4468 				optlen = 2;
4469 			hlen -= optlen;
4470 			opt += optlen;
4471 			break;
4472 		}
4473 	}
4474 	return (mss);
4475 }
4476 
4477 static u_int16_t
pf_calc_mss(struct pf_addr * addr,sa_family_t af,int rtableid,u_int16_t offer)4478 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
4479 {
4480 	struct nhop_object *nh;
4481 #ifdef INET6
4482 	struct in6_addr		dst6;
4483 	uint32_t		scopeid;
4484 #endif /* INET6 */
4485 	int			 hlen = 0;
4486 	uint16_t		 mss = 0;
4487 
4488 	NET_EPOCH_ASSERT();
4489 
4490 	switch (af) {
4491 #ifdef INET
4492 	case AF_INET:
4493 		hlen = sizeof(struct ip);
4494 		nh = fib4_lookup(rtableid, addr->v4, 0, 0, 0);
4495 		if (nh != NULL)
4496 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
4497 		break;
4498 #endif /* INET */
4499 #ifdef INET6
4500 	case AF_INET6:
4501 		hlen = sizeof(struct ip6_hdr);
4502 		in6_splitscope(&addr->v6, &dst6, &scopeid);
4503 		nh = fib6_lookup(rtableid, &dst6, scopeid, 0, 0);
4504 		if (nh != NULL)
4505 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
4506 		break;
4507 #endif /* INET6 */
4508 	}
4509 
4510 	mss = max(V_tcp_mssdflt, mss);
4511 	mss = min(mss, offer);
4512 	mss = max(mss, 64);		/* sanity - at least max opt space */
4513 	return (mss);
4514 }
4515 
4516 static u_int32_t
pf_tcp_iss(struct pf_pdesc * pd)4517 pf_tcp_iss(struct pf_pdesc *pd)
4518 {
4519 	MD5_CTX ctx;
4520 	u_int32_t digest[4];
4521 
4522 	if (V_pf_tcp_secret_init == 0) {
4523 		arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
4524 		MD5Init(&V_pf_tcp_secret_ctx);
4525 		MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
4526 		    sizeof(V_pf_tcp_secret));
4527 		V_pf_tcp_secret_init = 1;
4528 	}
4529 
4530 	ctx = V_pf_tcp_secret_ctx;
4531 
4532 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_sport, sizeof(u_short));
4533 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_dport, sizeof(u_short));
4534 	switch (pd->af) {
4535 	case AF_INET6:
4536 		MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
4537 		MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
4538 		break;
4539 	case AF_INET:
4540 		MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
4541 		MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
4542 		break;
4543 	}
4544 	MD5Final((u_char *)digest, &ctx);
4545 	V_pf_tcp_iss_off += 4096;
4546 #define	ISN_RANDOM_INCREMENT (4096 - 1)
4547 	return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
4548 	    V_pf_tcp_iss_off);
4549 #undef	ISN_RANDOM_INCREMENT
4550 }
4551 
4552 static bool
pf_match_eth_addr(const uint8_t * a,const struct pf_keth_rule_addr * r)4553 pf_match_eth_addr(const uint8_t *a, const struct pf_keth_rule_addr *r)
4554 {
4555 	bool match = true;
4556 
4557 	/* Always matches if not set */
4558 	if (! r->isset)
4559 		return (!r->neg);
4560 
4561 	for (int i = 0; i < ETHER_ADDR_LEN; i++) {
4562 		if ((a[i] & r->mask[i]) != (r->addr[i] & r->mask[i])) {
4563 			match = false;
4564 			break;
4565 		}
4566 	}
4567 
4568 	return (match ^ r->neg);
4569 }
4570 
4571 static int
pf_match_eth_tag(struct mbuf * m,struct pf_keth_rule * r,int * tag,int mtag)4572 pf_match_eth_tag(struct mbuf *m, struct pf_keth_rule *r, int *tag, int mtag)
4573 {
4574 	if (*tag == -1)
4575 		*tag = mtag;
4576 
4577 	return ((!r->match_tag_not && r->match_tag == *tag) ||
4578 	    (r->match_tag_not && r->match_tag != *tag));
4579 }
4580 
4581 static void
pf_bridge_to(struct ifnet * ifp,struct mbuf * m)4582 pf_bridge_to(struct ifnet *ifp, struct mbuf *m)
4583 {
4584 	/* If we don't have the interface drop the packet. */
4585 	if (ifp == NULL) {
4586 		m_freem(m);
4587 		return;
4588 	}
4589 
4590 	switch (ifp->if_type) {
4591 	case IFT_ETHER:
4592 	case IFT_XETHER:
4593 	case IFT_L2VLAN:
4594 	case IFT_BRIDGE:
4595 	case IFT_IEEE8023ADLAG:
4596 		break;
4597 	default:
4598 		m_freem(m);
4599 		return;
4600 	}
4601 
4602 	ifp->if_transmit(ifp, m);
4603 }
4604 
4605 static int
pf_test_eth_rule(int dir,struct pfi_kkif * kif,struct mbuf ** m0)4606 pf_test_eth_rule(int dir, struct pfi_kkif *kif, struct mbuf **m0)
4607 {
4608 #ifdef INET
4609 	struct ip ip;
4610 #endif
4611 #ifdef INET6
4612 	struct ip6_hdr ip6;
4613 #endif
4614 	struct mbuf *m = *m0;
4615 	struct ether_header *e;
4616 	struct pf_keth_rule *r, *rm, *a = NULL;
4617 	struct pf_keth_ruleset *ruleset = NULL;
4618 	struct pf_mtag *mtag;
4619 	struct pf_keth_ruleq *rules;
4620 	struct pf_addr *src = NULL, *dst = NULL;
4621 	struct pfi_kkif *bridge_to;
4622 	sa_family_t af = 0;
4623 	uint16_t proto;
4624 	int asd = 0, match = 0;
4625 	int tag = -1;
4626 	uint8_t action;
4627 	struct pf_keth_anchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4628 
4629 	MPASS(kif->pfik_ifp->if_vnet == curvnet);
4630 	NET_EPOCH_ASSERT();
4631 
4632 	PF_RULES_RLOCK_TRACKER;
4633 
4634 	SDT_PROBE3(pf, eth, test_rule, entry, dir, kif->pfik_ifp, m);
4635 
4636 	mtag = pf_find_mtag(m);
4637 	if (mtag != NULL && mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
4638 		/* Dummynet re-injects packets after they've
4639 		 * completed their delay. We've already
4640 		 * processed them, so pass unconditionally. */
4641 
4642 		/* But only once. We may see the packet multiple times (e.g.
4643 		 * PFIL_IN/PFIL_OUT). */
4644 		pf_dummynet_flag_remove(m, mtag);
4645 
4646 		return (PF_PASS);
4647 	}
4648 
4649 	ruleset = V_pf_keth;
4650 	rules = ck_pr_load_ptr(&ruleset->active.rules);
4651 	r = TAILQ_FIRST(rules);
4652 	rm = NULL;
4653 
4654 	if (__predict_false(m->m_len < sizeof(struct ether_header)) &&
4655 	    (m = *m0 = m_pullup(*m0, sizeof(struct ether_header))) == NULL) {
4656 		DPFPRINTF(PF_DEBUG_URGENT,
4657 		    ("pf_test_eth_rule: m_len < sizeof(struct ether_header)"
4658 		     ", pullup failed\n"));
4659 		return (PF_DROP);
4660 	}
4661 	e = mtod(m, struct ether_header *);
4662 	proto = ntohs(e->ether_type);
4663 
4664 	switch (proto) {
4665 #ifdef INET
4666 	case ETHERTYPE_IP: {
4667 		if (m_length(m, NULL) < (sizeof(struct ether_header) +
4668 		    sizeof(ip)))
4669 			return (PF_DROP);
4670 
4671 		af = AF_INET;
4672 		m_copydata(m, sizeof(struct ether_header), sizeof(ip),
4673 		    (caddr_t)&ip);
4674 		src = (struct pf_addr *)&ip.ip_src;
4675 		dst = (struct pf_addr *)&ip.ip_dst;
4676 		break;
4677 	}
4678 #endif /* INET */
4679 #ifdef INET6
4680 	case ETHERTYPE_IPV6: {
4681 		if (m_length(m, NULL) < (sizeof(struct ether_header) +
4682 		    sizeof(ip6)))
4683 			return (PF_DROP);
4684 
4685 		af = AF_INET6;
4686 		m_copydata(m, sizeof(struct ether_header), sizeof(ip6),
4687 		    (caddr_t)&ip6);
4688 		src = (struct pf_addr *)&ip6.ip6_src;
4689 		dst = (struct pf_addr *)&ip6.ip6_dst;
4690 		break;
4691 	}
4692 #endif /* INET6 */
4693 	}
4694 
4695 	PF_RULES_RLOCK();
4696 
4697 	while (r != NULL) {
4698 		counter_u64_add(r->evaluations, 1);
4699 		SDT_PROBE2(pf, eth, test_rule, test, r->nr, r);
4700 
4701 		if (pfi_kkif_match(r->kif, kif) == r->ifnot) {
4702 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4703 			    "kif");
4704 			r = r->skip[PFE_SKIP_IFP].ptr;
4705 		}
4706 		else if (r->direction && r->direction != dir) {
4707 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4708 			    "dir");
4709 			r = r->skip[PFE_SKIP_DIR].ptr;
4710 		}
4711 		else if (r->proto && r->proto != proto) {
4712 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4713 			    "proto");
4714 			r = r->skip[PFE_SKIP_PROTO].ptr;
4715 		}
4716 		else if (! pf_match_eth_addr(e->ether_shost, &r->src)) {
4717 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4718 			    "src");
4719 			r = r->skip[PFE_SKIP_SRC_ADDR].ptr;
4720 		}
4721 		else if (! pf_match_eth_addr(e->ether_dhost, &r->dst)) {
4722 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4723 			    "dst");
4724 			r = r->skip[PFE_SKIP_DST_ADDR].ptr;
4725 		}
4726 		else if (src != NULL && PF_MISMATCHAW(&r->ipsrc.addr, src, af,
4727 		    r->ipsrc.neg, kif, M_GETFIB(m))) {
4728 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4729 			    "ip_src");
4730 			r = r->skip[PFE_SKIP_SRC_IP_ADDR].ptr;
4731 		}
4732 		else if (dst != NULL && PF_MISMATCHAW(&r->ipdst.addr, dst, af,
4733 		    r->ipdst.neg, kif, M_GETFIB(m))) {
4734 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4735 			    "ip_dst");
4736 			r = r->skip[PFE_SKIP_DST_IP_ADDR].ptr;
4737 		}
4738 		else if (r->match_tag && !pf_match_eth_tag(m, r, &tag,
4739 		    mtag ? mtag->tag : 0)) {
4740 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4741 			    "match_tag");
4742 			r = TAILQ_NEXT(r, entries);
4743 		}
4744 		else {
4745 			if (r->tag)
4746 				tag = r->tag;
4747 			if (r->anchor == NULL) {
4748 				/* Rule matches */
4749 				rm = r;
4750 
4751 				SDT_PROBE2(pf, eth, test_rule, match, r->nr, r);
4752 
4753 				if (r->quick)
4754 					break;
4755 
4756 				r = TAILQ_NEXT(r, entries);
4757 			} else {
4758 				pf_step_into_keth_anchor(anchor_stack, &asd,
4759 				    &ruleset, &r, &a, &match);
4760 			}
4761 		}
4762 		if (r == NULL && pf_step_out_of_keth_anchor(anchor_stack, &asd,
4763 		    &ruleset, &r, &a, &match))
4764 			break;
4765 	}
4766 
4767 	r = rm;
4768 
4769 	SDT_PROBE2(pf, eth, test_rule, final_match, (r != NULL ? r->nr : -1), r);
4770 
4771 	/* Default to pass. */
4772 	if (r == NULL) {
4773 		PF_RULES_RUNLOCK();
4774 		return (PF_PASS);
4775 	}
4776 
4777 	/* Execute action. */
4778 	counter_u64_add(r->packets[dir == PF_OUT], 1);
4779 	counter_u64_add(r->bytes[dir == PF_OUT], m_length(m, NULL));
4780 	pf_update_timestamp(r);
4781 
4782 	/* Shortcut. Don't tag if we're just going to drop anyway. */
4783 	if (r->action == PF_DROP) {
4784 		PF_RULES_RUNLOCK();
4785 		return (PF_DROP);
4786 	}
4787 
4788 	if (tag > 0) {
4789 		if (mtag == NULL)
4790 			mtag = pf_get_mtag(m);
4791 		if (mtag == NULL) {
4792 			PF_RULES_RUNLOCK();
4793 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4794 			return (PF_DROP);
4795 		}
4796 		mtag->tag = tag;
4797 	}
4798 
4799 	if (r->qid != 0) {
4800 		if (mtag == NULL)
4801 			mtag = pf_get_mtag(m);
4802 		if (mtag == NULL) {
4803 			PF_RULES_RUNLOCK();
4804 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4805 			return (PF_DROP);
4806 		}
4807 		mtag->qid = r->qid;
4808 	}
4809 
4810 	action = r->action;
4811 	bridge_to = r->bridge_to;
4812 
4813 	/* Dummynet */
4814 	if (r->dnpipe) {
4815 		struct ip_fw_args dnflow;
4816 
4817 		/* Drop packet if dummynet is not loaded. */
4818 		if (ip_dn_io_ptr == NULL) {
4819 			PF_RULES_RUNLOCK();
4820 			m_freem(m);
4821 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4822 			return (PF_DROP);
4823 		}
4824 		if (mtag == NULL)
4825 			mtag = pf_get_mtag(m);
4826 		if (mtag == NULL) {
4827 			PF_RULES_RUNLOCK();
4828 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4829 			return (PF_DROP);
4830 		}
4831 
4832 		bzero(&dnflow, sizeof(dnflow));
4833 
4834 		/* We don't have port numbers here, so we set 0.  That means
4835 		 * that we'll be somewhat limited in distinguishing flows (i.e.
4836 		 * only based on IP addresses, not based on port numbers), but
4837 		 * it's better than nothing. */
4838 		dnflow.f_id.dst_port = 0;
4839 		dnflow.f_id.src_port = 0;
4840 		dnflow.f_id.proto = 0;
4841 
4842 		dnflow.rule.info = r->dnpipe;
4843 		dnflow.rule.info |= IPFW_IS_DUMMYNET;
4844 		if (r->dnflags & PFRULE_DN_IS_PIPE)
4845 			dnflow.rule.info |= IPFW_IS_PIPE;
4846 
4847 		dnflow.f_id.extra = dnflow.rule.info;
4848 
4849 		dnflow.flags = dir == PF_IN ? IPFW_ARGS_IN : IPFW_ARGS_OUT;
4850 		dnflow.flags |= IPFW_ARGS_ETHER;
4851 		dnflow.ifp = kif->pfik_ifp;
4852 
4853 		switch (af) {
4854 		case AF_INET:
4855 			dnflow.f_id.addr_type = 4;
4856 			dnflow.f_id.src_ip = src->v4.s_addr;
4857 			dnflow.f_id.dst_ip = dst->v4.s_addr;
4858 			break;
4859 		case AF_INET6:
4860 			dnflow.flags |= IPFW_ARGS_IP6;
4861 			dnflow.f_id.addr_type = 6;
4862 			dnflow.f_id.src_ip6 = src->v6;
4863 			dnflow.f_id.dst_ip6 = dst->v6;
4864 			break;
4865 		}
4866 
4867 		PF_RULES_RUNLOCK();
4868 
4869 		mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
4870 		ip_dn_io_ptr(m0, &dnflow);
4871 		if (*m0 != NULL)
4872 			pf_dummynet_flag_remove(m, mtag);
4873 	} else {
4874 		PF_RULES_RUNLOCK();
4875 	}
4876 
4877 	if (action == PF_PASS && bridge_to) {
4878 		pf_bridge_to(bridge_to->pfik_ifp, *m0);
4879 		*m0 = NULL; /* We've eaten the packet. */
4880 	}
4881 
4882 	return (action);
4883 }
4884 
4885 #define PF_TEST_ATTRIB(t, a)\
4886 	do {				\
4887 		if (t) {		\
4888 			r = a;		\
4889 			goto nextrule;	\
4890 		}			\
4891 	} while (0)
4892 
4893 static int
pf_test_rule(struct pf_krule ** rm,struct pf_kstate ** sm,struct pf_pdesc * pd,struct pf_krule ** am,struct pf_kruleset ** rsm,struct inpcb * inp)4894 pf_test_rule(struct pf_krule **rm, struct pf_kstate **sm,
4895     struct pf_pdesc *pd, struct pf_krule **am,
4896     struct pf_kruleset **rsm, struct inpcb *inp)
4897 {
4898 	struct pf_krule		*nr = NULL;
4899 	struct pf_addr		* const saddr = pd->src;
4900 	struct pf_addr		* const daddr = pd->dst;
4901 	struct pf_krule		*r, *a = NULL;
4902 	struct pf_kruleset	*ruleset = NULL;
4903 	struct pf_krule_slist	 match_rules;
4904 	struct pf_krule_item	*ri;
4905 	struct tcphdr		*th = &pd->hdr.tcp;
4906 	struct pf_state_key	*sk = NULL, *nk = NULL;
4907 	u_short			 reason, transerror;
4908 	int			 rewrite = 0;
4909 	int			 tag = -1;
4910 	int			 asd = 0;
4911 	int			 match = 0;
4912 	int			 state_icmp = 0, icmp_dir, multi;
4913 	u_int16_t		 sport = 0, dport = 0, virtual_type, virtual_id;
4914 	u_int16_t		 bproto_sum = 0, bip_sum = 0;
4915 	u_int8_t		 icmptype = 0, icmpcode = 0;
4916 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4917 	struct pf_udp_mapping	*udp_mapping = NULL;
4918 
4919 	PF_RULES_RASSERT();
4920 
4921 	SLIST_INIT(&match_rules);
4922 
4923 	if (inp != NULL) {
4924 		INP_LOCK_ASSERT(inp);
4925 		pd->lookup.uid = inp->inp_cred->cr_uid;
4926 		pd->lookup.gid = inp->inp_cred->cr_groups[0];
4927 		pd->lookup.done = 1;
4928 	}
4929 
4930 	switch (pd->virtual_proto) {
4931 	case IPPROTO_TCP:
4932 		sport = th->th_sport;
4933 		dport = th->th_dport;
4934 		break;
4935 	case IPPROTO_UDP:
4936 		sport = pd->hdr.udp.uh_sport;
4937 		dport = pd->hdr.udp.uh_dport;
4938 		break;
4939 	case IPPROTO_SCTP:
4940 		sport = pd->hdr.sctp.src_port;
4941 		dport = pd->hdr.sctp.dest_port;
4942 		break;
4943 #ifdef INET
4944 	case IPPROTO_ICMP:
4945 		MPASS(pd->af == AF_INET);
4946 		icmptype = pd->hdr.icmp.icmp_type;
4947 		icmpcode = pd->hdr.icmp.icmp_code;
4948 		state_icmp = pf_icmp_mapping(pd, icmptype,
4949 		    &icmp_dir, &multi, &virtual_id, &virtual_type);
4950 		if (icmp_dir == PF_IN) {
4951 			sport = virtual_id;
4952 			dport = virtual_type;
4953 		} else {
4954 			sport = virtual_type;
4955 			dport = virtual_id;
4956 		}
4957 		break;
4958 #endif /* INET */
4959 #ifdef INET6
4960 	case IPPROTO_ICMPV6:
4961 		MPASS(pd->af == AF_INET6);
4962 		icmptype = pd->hdr.icmp6.icmp6_type;
4963 		icmpcode = pd->hdr.icmp6.icmp6_code;
4964 		state_icmp = pf_icmp_mapping(pd, icmptype,
4965 		    &icmp_dir, &multi, &virtual_id, &virtual_type);
4966 		if (icmp_dir == PF_IN) {
4967 			sport = virtual_id;
4968 			dport = virtual_type;
4969 		} else {
4970 			sport = virtual_type;
4971 			dport = virtual_id;
4972 		}
4973 
4974 		break;
4975 #endif /* INET6 */
4976 	default:
4977 		sport = dport = 0;
4978 		break;
4979 	}
4980 
4981 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4982 
4983 	/* check packet for BINAT/NAT/RDR */
4984 	transerror = pf_get_translation(pd, pd->off, &sk, &nk, saddr, daddr,
4985 	    sport, dport, anchor_stack, &nr, &udp_mapping);
4986 	switch (transerror) {
4987 	default:
4988 		/* A translation error occurred. */
4989 		REASON_SET(&reason, transerror);
4990 		goto cleanup;
4991 	case PFRES_MAX:
4992 		/* No match. */
4993 		break;
4994 	case PFRES_MATCH:
4995 		KASSERT(sk != NULL, ("%s: null sk", __func__));
4996 		KASSERT(nk != NULL, ("%s: null nk", __func__));
4997 
4998 		if (nr->log) {
4999 			PFLOG_PACKET(PF_PASS, PFRES_MATCH, nr, a,
5000 			    ruleset, pd, 1);
5001 		}
5002 
5003 		if (pd->ip_sum)
5004 			bip_sum = *pd->ip_sum;
5005 
5006 		switch (pd->proto) {
5007 		case IPPROTO_TCP:
5008 			bproto_sum = th->th_sum;
5009 			pd->proto_sum = &th->th_sum;
5010 
5011 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], pd->af) ||
5012 			    nk->port[pd->sidx] != sport) {
5013 				pf_change_ap(pd->m, saddr, &th->th_sport, pd->ip_sum,
5014 				    &th->th_sum, &nk->addr[pd->sidx],
5015 				    nk->port[pd->sidx], 0, pd->af);
5016 				pd->sport = &th->th_sport;
5017 				sport = th->th_sport;
5018 			}
5019 
5020 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], pd->af) ||
5021 			    nk->port[pd->didx] != dport) {
5022 				pf_change_ap(pd->m, daddr, &th->th_dport, pd->ip_sum,
5023 				    &th->th_sum, &nk->addr[pd->didx],
5024 				    nk->port[pd->didx], 0, pd->af);
5025 				dport = th->th_dport;
5026 				pd->dport = &th->th_dport;
5027 			}
5028 			rewrite++;
5029 			break;
5030 		case IPPROTO_UDP:
5031 			bproto_sum = pd->hdr.udp.uh_sum;
5032 			pd->proto_sum = &pd->hdr.udp.uh_sum;
5033 
5034 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], pd->af) ||
5035 			    nk->port[pd->sidx] != sport) {
5036 				pf_change_ap(pd->m, saddr, &pd->hdr.udp.uh_sport,
5037 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
5038 				    &nk->addr[pd->sidx],
5039 				    nk->port[pd->sidx], 1, pd->af);
5040 				sport = pd->hdr.udp.uh_sport;
5041 				pd->sport = &pd->hdr.udp.uh_sport;
5042 			}
5043 
5044 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], pd->af) ||
5045 			    nk->port[pd->didx] != dport) {
5046 				pf_change_ap(pd->m, daddr, &pd->hdr.udp.uh_dport,
5047 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
5048 				    &nk->addr[pd->didx],
5049 				    nk->port[pd->didx], 1, pd->af);
5050 				dport = pd->hdr.udp.uh_dport;
5051 				pd->dport = &pd->hdr.udp.uh_dport;
5052 			}
5053 			rewrite++;
5054 			break;
5055 		case IPPROTO_SCTP: {
5056 			uint16_t checksum = 0;
5057 
5058 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], pd->af) ||
5059 			    nk->port[pd->sidx] != sport) {
5060 				pf_change_ap(pd->m, saddr, &pd->hdr.sctp.src_port,
5061 				    pd->ip_sum, &checksum,
5062 				    &nk->addr[pd->sidx],
5063 				    nk->port[pd->sidx], 1, pd->af);
5064 			}
5065 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], pd->af) ||
5066 			    nk->port[pd->didx] != dport) {
5067 				pf_change_ap(pd->m, daddr, &pd->hdr.sctp.dest_port,
5068 				    pd->ip_sum, &checksum,
5069 				    &nk->addr[pd->didx],
5070 				    nk->port[pd->didx], 1, pd->af);
5071 			}
5072 			break;
5073 		}
5074 #ifdef INET
5075 		case IPPROTO_ICMP:
5076 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
5077 				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
5078 				    nk->addr[pd->sidx].v4.s_addr, 0);
5079 
5080 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
5081 				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
5082 				    nk->addr[pd->didx].v4.s_addr, 0);
5083 
5084 			if (virtual_type == htons(ICMP_ECHO) &&
5085 			     nk->port[pd->sidx] != pd->hdr.icmp.icmp_id) {
5086 				pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
5087 				    pd->hdr.icmp.icmp_cksum, sport,
5088 				    nk->port[pd->sidx], 0);
5089 				pd->hdr.icmp.icmp_id = nk->port[pd->sidx];
5090 				pd->sport = &pd->hdr.icmp.icmp_id;
5091 			}
5092 			m_copyback(pd->m, pd->off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
5093 			break;
5094 #endif /* INET */
5095 #ifdef INET6
5096 		case IPPROTO_ICMPV6:
5097 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
5098 				pf_change_a6(saddr, &pd->hdr.icmp6.icmp6_cksum,
5099 				    &nk->addr[pd->sidx], 0);
5100 
5101 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
5102 				pf_change_a6(daddr, &pd->hdr.icmp6.icmp6_cksum,
5103 				    &nk->addr[pd->didx], 0);
5104 			rewrite++;
5105 			break;
5106 #endif /* INET */
5107 		default:
5108 			switch (pd->af) {
5109 #ifdef INET
5110 			case AF_INET:
5111 				if (PF_ANEQ(saddr,
5112 				    &nk->addr[pd->sidx], AF_INET))
5113 					pf_change_a(&saddr->v4.s_addr,
5114 					    pd->ip_sum,
5115 					    nk->addr[pd->sidx].v4.s_addr, 0);
5116 
5117 				if (PF_ANEQ(daddr,
5118 				    &nk->addr[pd->didx], AF_INET))
5119 					pf_change_a(&daddr->v4.s_addr,
5120 					    pd->ip_sum,
5121 					    nk->addr[pd->didx].v4.s_addr, 0);
5122 				break;
5123 #endif /* INET */
5124 #ifdef INET6
5125 			case AF_INET6:
5126 				if (PF_ANEQ(saddr,
5127 				    &nk->addr[pd->sidx], AF_INET6))
5128 					PF_ACPY(saddr, &nk->addr[pd->sidx], pd->af);
5129 
5130 				if (PF_ANEQ(daddr,
5131 				    &nk->addr[pd->didx], AF_INET6))
5132 					PF_ACPY(daddr, &nk->addr[pd->didx], pd->af);
5133 				break;
5134 #endif /* INET */
5135 			}
5136 			break;
5137 		}
5138 		if (nr->natpass)
5139 			r = NULL;
5140 	}
5141 
5142 	while (r != NULL) {
5143 		pf_counter_u64_add(&r->evaluations, 1);
5144 		PF_TEST_ATTRIB(pfi_kkif_match(r->kif, pd->kif) == r->ifnot,
5145 			r->skip[PF_SKIP_IFP]);
5146 		PF_TEST_ATTRIB(r->direction && r->direction != pd->dir,
5147 			r->skip[PF_SKIP_DIR]);
5148 		PF_TEST_ATTRIB(r->af && r->af != pd->af,
5149 			r->skip[PF_SKIP_AF]);
5150 		PF_TEST_ATTRIB(r->proto && r->proto != pd->proto,
5151 			r->skip[PF_SKIP_PROTO]);
5152 		PF_TEST_ATTRIB(PF_MISMATCHAW(&r->src.addr, saddr, pd->af,
5153 		    r->src.neg, pd->kif, M_GETFIB(pd->m)),
5154 			r->skip[PF_SKIP_SRC_ADDR]);
5155 		PF_TEST_ATTRIB(PF_MISMATCHAW(&r->dst.addr, daddr, pd->af,
5156 		    r->dst.neg, NULL, M_GETFIB(pd->m)),
5157 			r->skip[PF_SKIP_DST_ADDR]);
5158 		switch (pd->virtual_proto) {
5159 		case PF_VPROTO_FRAGMENT:
5160 			/* tcp/udp only. port_op always 0 in other cases */
5161 			PF_TEST_ATTRIB((r->src.port_op || r->dst.port_op),
5162 				TAILQ_NEXT(r, entries));
5163 			PF_TEST_ATTRIB((pd->proto == IPPROTO_TCP && r->flagset),
5164 				TAILQ_NEXT(r, entries));
5165 			/* icmp only. type/code always 0 in other cases */
5166 			PF_TEST_ATTRIB((r->type || r->code),
5167 				TAILQ_NEXT(r, entries));
5168 			/* tcp/udp only. {uid|gid}.op always 0 in other cases */
5169 			PF_TEST_ATTRIB((r->gid.op || r->uid.op),
5170 				TAILQ_NEXT(r, entries));
5171 			break;
5172 
5173 		case IPPROTO_TCP:
5174 			PF_TEST_ATTRIB((r->flagset & tcp_get_flags(th)) != r->flags,
5175 				TAILQ_NEXT(r, entries));
5176 			/* FALLTHROUGH */
5177 		case IPPROTO_SCTP:
5178 		case IPPROTO_UDP:
5179 			/* tcp/udp only. port_op always 0 in other cases */
5180 			PF_TEST_ATTRIB(r->src.port_op && !pf_match_port(r->src.port_op,
5181 			    r->src.port[0], r->src.port[1], sport),
5182 				r->skip[PF_SKIP_SRC_PORT]);
5183 			/* tcp/udp only. port_op always 0 in other cases */
5184 			PF_TEST_ATTRIB(r->dst.port_op && !pf_match_port(r->dst.port_op,
5185 			    r->dst.port[0], r->dst.port[1], dport),
5186 				r->skip[PF_SKIP_DST_PORT]);
5187 			/* tcp/udp only. uid.op always 0 in other cases */
5188 			PF_TEST_ATTRIB(r->uid.op && (pd->lookup.done || (pd->lookup.done =
5189 			    pf_socket_lookup(pd), 1)) &&
5190 			    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
5191 			    pd->lookup.uid),
5192 				TAILQ_NEXT(r, entries));
5193 			/* tcp/udp only. gid.op always 0 in other cases */
5194 			PF_TEST_ATTRIB(r->gid.op && (pd->lookup.done || (pd->lookup.done =
5195 			    pf_socket_lookup(pd), 1)) &&
5196 			    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
5197 			    pd->lookup.gid),
5198 				TAILQ_NEXT(r, entries));
5199 			break;
5200 
5201 		case IPPROTO_ICMP:
5202 		case IPPROTO_ICMPV6:
5203 			/* icmp only. type always 0 in other cases */
5204 			PF_TEST_ATTRIB(r->type && r->type != icmptype + 1,
5205 				TAILQ_NEXT(r, entries));
5206 			/* icmp only. type always 0 in other cases */
5207 			PF_TEST_ATTRIB(r->code && r->code != icmpcode + 1,
5208 				TAILQ_NEXT(r, entries));
5209 			break;
5210 
5211 		default:
5212 			break;
5213 		}
5214 		PF_TEST_ATTRIB(r->tos && !(r->tos == pd->tos),
5215 			TAILQ_NEXT(r, entries));
5216 		PF_TEST_ATTRIB(r->prio &&
5217 		    !pf_match_ieee8021q_pcp(r->prio, pd->m),
5218 			TAILQ_NEXT(r, entries));
5219 		PF_TEST_ATTRIB(r->prob &&
5220 		    r->prob <= arc4random(),
5221 			TAILQ_NEXT(r, entries));
5222 		PF_TEST_ATTRIB(r->match_tag && !pf_match_tag(pd->m, r, &tag,
5223 		    pd->pf_mtag ? pd->pf_mtag->tag : 0),
5224 			TAILQ_NEXT(r, entries));
5225 		PF_TEST_ATTRIB(r->rcv_kif && !pf_match_rcvif(pd->m, r),
5226 			TAILQ_NEXT(r, entries));
5227 		PF_TEST_ATTRIB((r->rule_flag & PFRULE_FRAGMENT &&
5228 		    pd->virtual_proto != PF_VPROTO_FRAGMENT),
5229 			TAILQ_NEXT(r, entries));
5230 		PF_TEST_ATTRIB(r->os_fingerprint != PF_OSFP_ANY &&
5231 		    (pd->virtual_proto != IPPROTO_TCP || !pf_osfp_match(
5232 		    pf_osfp_fingerprint(pd, th),
5233 		    r->os_fingerprint)),
5234 			TAILQ_NEXT(r, entries));
5235 		/* FALLTHROUGH */
5236 		if (r->tag)
5237 			tag = r->tag;
5238 		if (r->anchor == NULL) {
5239 			if (r->action == PF_MATCH) {
5240 				ri = malloc(sizeof(struct pf_krule_item), M_PF_RULE_ITEM, M_NOWAIT | M_ZERO);
5241 				if (ri == NULL) {
5242 					REASON_SET(&reason, PFRES_MEMORY);
5243 					goto cleanup;
5244 				}
5245 				ri->r = r;
5246 				SLIST_INSERT_HEAD(&match_rules, ri, entry);
5247 				pf_counter_u64_critical_enter();
5248 				pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
5249 				pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
5250 				pf_counter_u64_critical_exit();
5251 				pf_rule_to_actions(r, &pd->act);
5252 				if (r->log || pd->act.log & PF_LOG_MATCHES)
5253 					PFLOG_PACKET(r->action, PFRES_MATCH, r,
5254 					    a, ruleset, pd, 1);
5255 			} else {
5256 				match = 1;
5257 				*rm = r;
5258 				*am = a;
5259 				*rsm = ruleset;
5260 				if (pd->act.log & PF_LOG_MATCHES)
5261 					PFLOG_PACKET(r->action, PFRES_MATCH, r,
5262 					    a, ruleset, pd, 1);
5263 			}
5264 			if ((*rm)->quick)
5265 				break;
5266 			r = TAILQ_NEXT(r, entries);
5267 		} else
5268 			pf_step_into_anchor(anchor_stack, &asd,
5269 			    &ruleset, PF_RULESET_FILTER, &r, &a,
5270 			    &match);
5271 nextrule:
5272 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
5273 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
5274 			break;
5275 	}
5276 	r = *rm;
5277 	a = *am;
5278 	ruleset = *rsm;
5279 
5280 	REASON_SET(&reason, PFRES_MATCH);
5281 
5282 	/* apply actions for last matching pass/block rule */
5283 	pf_rule_to_actions(r, &pd->act);
5284 
5285 	if (r->log || pd->act.log & PF_LOG_MATCHES) {
5286 		if (rewrite)
5287 			m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
5288 		PFLOG_PACKET(r->action, reason, r, a, ruleset, pd, 1);
5289 	}
5290 
5291 	if (pd->virtual_proto != PF_VPROTO_FRAGMENT &&
5292 	   (r->action == PF_DROP) &&
5293 	    ((r->rule_flag & PFRULE_RETURNRST) ||
5294 	    (r->rule_flag & PFRULE_RETURNICMP) ||
5295 	    (r->rule_flag & PFRULE_RETURN))) {
5296 		pf_return(r, nr, pd, sk, th, bproto_sum,
5297 		    bip_sum, &reason, r->rtableid);
5298 	}
5299 
5300 	if (r->action == PF_DROP)
5301 		goto cleanup;
5302 
5303 	if (tag > 0 && pf_tag_packet(pd, tag)) {
5304 		REASON_SET(&reason, PFRES_MEMORY);
5305 		goto cleanup;
5306 	}
5307 	if (pd->act.rtableid >= 0)
5308 		M_SETFIB(pd->m, pd->act.rtableid);
5309 
5310 	if (pd->virtual_proto != PF_VPROTO_FRAGMENT &&
5311 	   (!state_icmp && (r->keep_state || nr != NULL ||
5312 	    (pd->flags & PFDESC_TCP_NORM)))) {
5313 		int action;
5314 		action = pf_create_state(r, nr, a, pd, nk, sk,
5315 		    sport, dport, &rewrite, sm, tag, bproto_sum, bip_sum,
5316 		    &match_rules, udp_mapping);
5317 		if (action != PF_PASS) {
5318 			pf_udp_mapping_release(udp_mapping);
5319 			if (action == PF_DROP &&
5320 			    (r->rule_flag & PFRULE_RETURN))
5321 				pf_return(r, nr, pd, sk, th,
5322 				    bproto_sum, bip_sum, &reason,
5323 				    pd->act.rtableid);
5324 			return (action);
5325 		}
5326 	} else {
5327 		while ((ri = SLIST_FIRST(&match_rules))) {
5328 			SLIST_REMOVE_HEAD(&match_rules, entry);
5329 			free(ri, M_PF_RULE_ITEM);
5330 		}
5331 
5332 		uma_zfree(V_pf_state_key_z, sk);
5333 		uma_zfree(V_pf_state_key_z, nk);
5334 		pf_udp_mapping_release(udp_mapping);
5335 	}
5336 
5337 	/* copy back packet headers if we performed NAT operations */
5338 	if (rewrite)
5339 		m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
5340 
5341 	if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
5342 	    pd->dir == PF_OUT &&
5343 	    V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, pd->m))
5344 		/*
5345 		 * We want the state created, but we dont
5346 		 * want to send this in case a partner
5347 		 * firewall has to know about it to allow
5348 		 * replies through it.
5349 		 */
5350 		return (PF_DEFER);
5351 
5352 	return (PF_PASS);
5353 
5354 cleanup:
5355 	while ((ri = SLIST_FIRST(&match_rules))) {
5356 		SLIST_REMOVE_HEAD(&match_rules, entry);
5357 		free(ri, M_PF_RULE_ITEM);
5358 	}
5359 
5360 	uma_zfree(V_pf_state_key_z, sk);
5361 	uma_zfree(V_pf_state_key_z, nk);
5362 	pf_udp_mapping_release(udp_mapping);
5363 
5364 	return (PF_DROP);
5365 }
5366 
5367 static int
pf_create_state(struct pf_krule * r,struct pf_krule * nr,struct pf_krule * a,struct pf_pdesc * pd,struct pf_state_key * nk,struct pf_state_key * sk,u_int16_t sport,u_int16_t dport,int * rewrite,struct pf_kstate ** sm,int tag,u_int16_t bproto_sum,u_int16_t bip_sum,struct pf_krule_slist * match_rules,struct pf_udp_mapping * udp_mapping)5368 pf_create_state(struct pf_krule *r, struct pf_krule *nr, struct pf_krule *a,
5369     struct pf_pdesc *pd, struct pf_state_key *nk, struct pf_state_key *sk,
5370     u_int16_t sport, u_int16_t dport, int *rewrite, struct pf_kstate **sm,
5371     int tag, u_int16_t bproto_sum, u_int16_t bip_sum,
5372     struct pf_krule_slist *match_rules, struct pf_udp_mapping *udp_mapping)
5373 {
5374 	struct pf_kstate	*s = NULL;
5375 	struct pf_ksrc_node	*sn = NULL;
5376 	struct pf_srchash	*snh = NULL;
5377 	struct pf_ksrc_node	*nsn = NULL;
5378 	struct pf_srchash	*nsnh = NULL;
5379 	struct tcphdr		*th = &pd->hdr.tcp;
5380 	u_int16_t		 mss = V_tcp_mssdflt;
5381 	u_short			 reason, sn_reason;
5382 	struct pf_krule_item	*ri;
5383 
5384 	/* check maximums */
5385 	if (r->max_states &&
5386 	    (counter_u64_fetch(r->states_cur) >= r->max_states)) {
5387 		counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
5388 		REASON_SET(&reason, PFRES_MAXSTATES);
5389 		goto csfailed;
5390 	}
5391 	/* src node for filter rule */
5392 	if ((r->rule_flag & PFRULE_SRCTRACK ||
5393 	    r->rpool.opts & PF_POOL_STICKYADDR) &&
5394 	    (sn_reason = pf_insert_src_node(&sn, &snh, r, pd->src, pd->af)) != 0) {
5395 		REASON_SET(&reason, sn_reason);
5396 		goto csfailed;
5397 	}
5398 	/* src node for translation rule */
5399 	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
5400 	    (sn_reason = pf_insert_src_node(&nsn, &nsnh, nr, &sk->addr[pd->sidx],
5401 	    pd->af)) != 0 ) {
5402 		REASON_SET(&reason, sn_reason);
5403 		goto csfailed;
5404 	}
5405 	s = pf_alloc_state(M_NOWAIT);
5406 	if (s == NULL) {
5407 		REASON_SET(&reason, PFRES_MEMORY);
5408 		goto csfailed;
5409 	}
5410 	s->rule = r;
5411 	s->nat_rule = nr;
5412 	s->anchor = a;
5413 	bcopy(match_rules, &s->match_rules, sizeof(s->match_rules));
5414 	memcpy(&s->act, &pd->act, sizeof(struct pf_rule_actions));
5415 
5416 	STATE_INC_COUNTERS(s);
5417 	if (r->allow_opts)
5418 		s->state_flags |= PFSTATE_ALLOWOPTS;
5419 	if (r->rule_flag & PFRULE_STATESLOPPY)
5420 		s->state_flags |= PFSTATE_SLOPPY;
5421 	if (pd->flags & PFDESC_TCP_NORM) /* Set by old-style scrub rules */
5422 		s->state_flags |= PFSTATE_SCRUB_TCP;
5423 	if ((r->rule_flag & PFRULE_PFLOW) ||
5424 	    (nr != NULL && nr->rule_flag & PFRULE_PFLOW))
5425 		s->state_flags |= PFSTATE_PFLOW;
5426 
5427 	s->act.log = pd->act.log & PF_LOG_ALL;
5428 	s->sync_state = PFSYNC_S_NONE;
5429 	s->state_flags |= pd->act.flags; /* Only needed for pfsync and state export */
5430 
5431 	if (nr != NULL)
5432 		s->act.log |= nr->log & PF_LOG_ALL;
5433 	switch (pd->proto) {
5434 	case IPPROTO_TCP:
5435 		s->src.seqlo = ntohl(th->th_seq);
5436 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
5437 		if ((tcp_get_flags(th) & (TH_SYN|TH_ACK)) == TH_SYN &&
5438 		    r->keep_state == PF_STATE_MODULATE) {
5439 			/* Generate sequence number modulator */
5440 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
5441 			    0)
5442 				s->src.seqdiff = 1;
5443 			pf_change_proto_a(pd->m, &th->th_seq, &th->th_sum,
5444 			    htonl(s->src.seqlo + s->src.seqdiff), 0);
5445 			*rewrite = 1;
5446 		} else
5447 			s->src.seqdiff = 0;
5448 		if (tcp_get_flags(th) & TH_SYN) {
5449 			s->src.seqhi++;
5450 			s->src.wscale = pf_get_wscale(pd);
5451 		}
5452 		s->src.max_win = MAX(ntohs(th->th_win), 1);
5453 		if (s->src.wscale & PF_WSCALE_MASK) {
5454 			/* Remove scale factor from initial window */
5455 			int win = s->src.max_win;
5456 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
5457 			s->src.max_win = (win - 1) >>
5458 			    (s->src.wscale & PF_WSCALE_MASK);
5459 		}
5460 		if (tcp_get_flags(th) & TH_FIN)
5461 			s->src.seqhi++;
5462 		s->dst.seqhi = 1;
5463 		s->dst.max_win = 1;
5464 		pf_set_protostate(s, PF_PEER_SRC, TCPS_SYN_SENT);
5465 		pf_set_protostate(s, PF_PEER_DST, TCPS_CLOSED);
5466 		s->timeout = PFTM_TCP_FIRST_PACKET;
5467 		atomic_add_32(&V_pf_status.states_halfopen, 1);
5468 		break;
5469 	case IPPROTO_UDP:
5470 		pf_set_protostate(s, PF_PEER_SRC, PFUDPS_SINGLE);
5471 		pf_set_protostate(s, PF_PEER_DST, PFUDPS_NO_TRAFFIC);
5472 		s->timeout = PFTM_UDP_FIRST_PACKET;
5473 		break;
5474 	case IPPROTO_SCTP:
5475 		pf_set_protostate(s, PF_PEER_SRC, SCTP_COOKIE_WAIT);
5476 		pf_set_protostate(s, PF_PEER_DST, SCTP_CLOSED);
5477 		s->timeout = PFTM_SCTP_FIRST_PACKET;
5478 		break;
5479 	case IPPROTO_ICMP:
5480 #ifdef INET6
5481 	case IPPROTO_ICMPV6:
5482 #endif
5483 		s->timeout = PFTM_ICMP_FIRST_PACKET;
5484 		break;
5485 	default:
5486 		pf_set_protostate(s, PF_PEER_SRC, PFOTHERS_SINGLE);
5487 		pf_set_protostate(s, PF_PEER_DST, PFOTHERS_NO_TRAFFIC);
5488 		s->timeout = PFTM_OTHER_FIRST_PACKET;
5489 	}
5490 
5491 	if (r->rt) {
5492 		/* pf_map_addr increases the reason counters */
5493 		if ((reason = pf_map_addr_sn(pd->af, r, pd->src, &s->rt_addr,
5494 		    &s->rt_kif, NULL, &sn, &snh)) != 0)
5495 			goto csfailed;
5496 		s->rt = r->rt;
5497 	}
5498 
5499 	s->creation = s->expire = pf_get_uptime();
5500 
5501 	if (pd->proto == IPPROTO_TCP) {
5502 		if (s->state_flags & PFSTATE_SCRUB_TCP &&
5503 		    pf_normalize_tcp_init(pd, th, &s->src, &s->dst)) {
5504 			REASON_SET(&reason, PFRES_MEMORY);
5505 			goto csfailed;
5506 		}
5507 		if (s->state_flags & PFSTATE_SCRUB_TCP && s->src.scrub &&
5508 		    pf_normalize_tcp_stateful(pd, &reason, th, s,
5509 		    &s->src, &s->dst, rewrite)) {
5510 			/* This really shouldn't happen!!! */
5511 			DPFPRINTF(PF_DEBUG_URGENT,
5512 			    ("pf_normalize_tcp_stateful failed on first "
5513 			     "pkt\n"));
5514 			goto csfailed;
5515 		}
5516 	} else if (pd->proto == IPPROTO_SCTP) {
5517 		if (pf_normalize_sctp_init(pd, &s->src, &s->dst))
5518 			goto csfailed;
5519 		if (! (pd->sctp_flags & (PFDESC_SCTP_INIT | PFDESC_SCTP_ADD_IP)))
5520 			goto csfailed;
5521 	}
5522 	s->direction = pd->dir;
5523 
5524 	/*
5525 	 * sk/nk could already been setup by pf_get_translation().
5526 	 */
5527 	if (nr == NULL) {
5528 		KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
5529 		    __func__, nr, sk, nk));
5530 		sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
5531 		if (sk == NULL)
5532 			goto csfailed;
5533 		nk = sk;
5534 	} else
5535 		KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
5536 		    __func__, nr, sk, nk));
5537 
5538 	/* Swap sk/nk for PF_OUT. */
5539 	if (pf_state_insert(BOUND_IFACE(s, pd->kif), pd->kif,
5540 	    (pd->dir == PF_IN) ? sk : nk,
5541 	    (pd->dir == PF_IN) ? nk : sk, s)) {
5542 		REASON_SET(&reason, PFRES_STATEINS);
5543 		goto drop;
5544 	} else
5545 		*sm = s;
5546 
5547 	/*
5548 	 * Lock order is important: first state, then source node.
5549 	 */
5550 	if (pf_src_node_exists(&sn, snh)) {
5551 		s->src_node = sn;
5552 		PF_HASHROW_UNLOCK(snh);
5553 	}
5554 	if (pf_src_node_exists(&nsn, nsnh)) {
5555 		/* XXX We only modify one side for now. */
5556 		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
5557 		s->nat_src_node = nsn;
5558 		PF_HASHROW_UNLOCK(nsnh);
5559 	}
5560 
5561 	if (tag > 0)
5562 		s->tag = tag;
5563 	if (pd->proto == IPPROTO_TCP && (tcp_get_flags(th) & (TH_SYN|TH_ACK)) ==
5564 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
5565 		pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_SRC);
5566 		/* undo NAT changes, if they have taken place */
5567 		if (nr != NULL) {
5568 			struct pf_state_key *skt = s->key[PF_SK_WIRE];
5569 			if (pd->dir == PF_OUT)
5570 				skt = s->key[PF_SK_STACK];
5571 			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
5572 			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
5573 			if (pd->sport)
5574 				*pd->sport = skt->port[pd->sidx];
5575 			if (pd->dport)
5576 				*pd->dport = skt->port[pd->didx];
5577 			if (pd->proto_sum)
5578 				*pd->proto_sum = bproto_sum;
5579 			if (pd->ip_sum)
5580 				*pd->ip_sum = bip_sum;
5581 			m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
5582 		}
5583 		s->src.seqhi = htonl(arc4random());
5584 		/* Find mss option */
5585 		int rtid = M_GETFIB(pd->m);
5586 		mss = pf_get_mss(pd);
5587 		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
5588 		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
5589 		s->src.mss = mss;
5590 		pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
5591 		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
5592 		    TH_SYN|TH_ACK, 0, s->src.mss, 0, M_SKIP_FIREWALL, 0, 0,
5593 		    pd->act.rtableid);
5594 		REASON_SET(&reason, PFRES_SYNPROXY);
5595 		return (PF_SYNPROXY_DROP);
5596 	}
5597 
5598 	s->udp_mapping = udp_mapping;
5599 
5600 	return (PF_PASS);
5601 
5602 csfailed:
5603 	while ((ri = SLIST_FIRST(match_rules))) {
5604 		SLIST_REMOVE_HEAD(match_rules, entry);
5605 		free(ri, M_PF_RULE_ITEM);
5606 	}
5607 
5608 	uma_zfree(V_pf_state_key_z, sk);
5609 	uma_zfree(V_pf_state_key_z, nk);
5610 
5611 	if (pf_src_node_exists(&sn, snh)) {
5612 		if (--sn->states == 0 && sn->expire == 0) {
5613 			pf_unlink_src_node(sn);
5614 			pf_free_src_node(sn);
5615 			counter_u64_add(
5616 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
5617 		}
5618 		PF_HASHROW_UNLOCK(snh);
5619 	}
5620 
5621 	if (sn != nsn && pf_src_node_exists(&nsn, nsnh)) {
5622 		if (--nsn->states == 0 && nsn->expire == 0) {
5623 			pf_unlink_src_node(nsn);
5624 			pf_free_src_node(nsn);
5625 			counter_u64_add(
5626 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
5627 		}
5628 		PF_HASHROW_UNLOCK(nsnh);
5629 	}
5630 
5631 drop:
5632 	if (s != NULL) {
5633 		pf_src_tree_remove_state(s);
5634 		s->timeout = PFTM_UNLINKED;
5635 		STATE_DEC_COUNTERS(s);
5636 		pf_free_state(s);
5637 	}
5638 
5639 	return (PF_DROP);
5640 }
5641 
5642 static int
pf_tcp_track_full(struct pf_kstate ** state,struct pf_pdesc * pd,u_short * reason,int * copyback)5643 pf_tcp_track_full(struct pf_kstate **state, struct pf_pdesc *pd,
5644     u_short *reason, int *copyback)
5645 {
5646 	struct tcphdr		*th = &pd->hdr.tcp;
5647 	struct pf_state_peer	*src, *dst;
5648 	u_int16_t		 win = ntohs(th->th_win);
5649 	u_int32_t		 ack, end, data_end, seq, orig_seq;
5650 	u_int8_t		 sws, dws, psrc, pdst;
5651 	int			 ackskew;
5652 
5653 	if (pd->dir == (*state)->direction) {
5654 		src = &(*state)->src;
5655 		dst = &(*state)->dst;
5656 		psrc = PF_PEER_SRC;
5657 		pdst = PF_PEER_DST;
5658 	} else {
5659 		src = &(*state)->dst;
5660 		dst = &(*state)->src;
5661 		psrc = PF_PEER_DST;
5662 		pdst = PF_PEER_SRC;
5663 	}
5664 
5665 	if (src->wscale && dst->wscale && !(tcp_get_flags(th) & TH_SYN)) {
5666 		sws = src->wscale & PF_WSCALE_MASK;
5667 		dws = dst->wscale & PF_WSCALE_MASK;
5668 	} else
5669 		sws = dws = 0;
5670 
5671 	/*
5672 	 * Sequence tracking algorithm from Guido van Rooij's paper:
5673 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
5674 	 *	tcp_filtering.ps
5675 	 */
5676 
5677 	orig_seq = seq = ntohl(th->th_seq);
5678 	if (src->seqlo == 0) {
5679 		/* First packet from this end. Set its state */
5680 
5681 		if (((*state)->state_flags & PFSTATE_SCRUB_TCP || dst->scrub) &&
5682 		    src->scrub == NULL) {
5683 			if (pf_normalize_tcp_init(pd, th, src, dst)) {
5684 				REASON_SET(reason, PFRES_MEMORY);
5685 				return (PF_DROP);
5686 			}
5687 		}
5688 
5689 		/* Deferred generation of sequence number modulator */
5690 		if (dst->seqdiff && !src->seqdiff) {
5691 			/* use random iss for the TCP server */
5692 			while ((src->seqdiff = arc4random() - seq) == 0)
5693 				;
5694 			ack = ntohl(th->th_ack) - dst->seqdiff;
5695 			pf_change_proto_a(pd->m, &th->th_seq, &th->th_sum, htonl(seq +
5696 			    src->seqdiff), 0);
5697 			pf_change_proto_a(pd->m, &th->th_ack, &th->th_sum, htonl(ack), 0);
5698 			*copyback = 1;
5699 		} else {
5700 			ack = ntohl(th->th_ack);
5701 		}
5702 
5703 		end = seq + pd->p_len;
5704 		if (tcp_get_flags(th) & TH_SYN) {
5705 			end++;
5706 			if (dst->wscale & PF_WSCALE_FLAG) {
5707 				src->wscale = pf_get_wscale(pd);
5708 				if (src->wscale & PF_WSCALE_FLAG) {
5709 					/* Remove scale factor from initial
5710 					 * window */
5711 					sws = src->wscale & PF_WSCALE_MASK;
5712 					win = ((u_int32_t)win + (1 << sws) - 1)
5713 					    >> sws;
5714 					dws = dst->wscale & PF_WSCALE_MASK;
5715 				} else {
5716 					/* fixup other window */
5717 					dst->max_win = MIN(TCP_MAXWIN,
5718 					    (u_int32_t)dst->max_win <<
5719 					    (dst->wscale & PF_WSCALE_MASK));
5720 					/* in case of a retrans SYN|ACK */
5721 					dst->wscale = 0;
5722 				}
5723 			}
5724 		}
5725 		data_end = end;
5726 		if (tcp_get_flags(th) & TH_FIN)
5727 			end++;
5728 
5729 		src->seqlo = seq;
5730 		if (src->state < TCPS_SYN_SENT)
5731 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5732 
5733 		/*
5734 		 * May need to slide the window (seqhi may have been set by
5735 		 * the crappy stack check or if we picked up the connection
5736 		 * after establishment)
5737 		 */
5738 		if (src->seqhi == 1 ||
5739 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
5740 			src->seqhi = end + MAX(1, dst->max_win << dws);
5741 		if (win > src->max_win)
5742 			src->max_win = win;
5743 
5744 	} else {
5745 		ack = ntohl(th->th_ack) - dst->seqdiff;
5746 		if (src->seqdiff) {
5747 			/* Modulate sequence numbers */
5748 			pf_change_proto_a(pd->m, &th->th_seq, &th->th_sum, htonl(seq +
5749 			    src->seqdiff), 0);
5750 			pf_change_proto_a(pd->m, &th->th_ack, &th->th_sum, htonl(ack), 0);
5751 			*copyback = 1;
5752 		}
5753 		end = seq + pd->p_len;
5754 		if (tcp_get_flags(th) & TH_SYN)
5755 			end++;
5756 		data_end = end;
5757 		if (tcp_get_flags(th) & TH_FIN)
5758 			end++;
5759 	}
5760 
5761 	if ((tcp_get_flags(th) & TH_ACK) == 0) {
5762 		/* Let it pass through the ack skew check */
5763 		ack = dst->seqlo;
5764 	} else if ((ack == 0 &&
5765 	    (tcp_get_flags(th) & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
5766 	    /* broken tcp stacks do not set ack */
5767 	    (dst->state < TCPS_SYN_SENT)) {
5768 		/*
5769 		 * Many stacks (ours included) will set the ACK number in an
5770 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
5771 		 */
5772 		ack = dst->seqlo;
5773 	}
5774 
5775 	if (seq == end) {
5776 		/* Ease sequencing restrictions on no data packets */
5777 		seq = src->seqlo;
5778 		data_end = end = seq;
5779 	}
5780 
5781 	ackskew = dst->seqlo - ack;
5782 
5783 	/*
5784 	 * Need to demodulate the sequence numbers in any TCP SACK options
5785 	 * (Selective ACK). We could optionally validate the SACK values
5786 	 * against the current ACK window, either forwards or backwards, but
5787 	 * I'm not confident that SACK has been implemented properly
5788 	 * everywhere. It wouldn't surprise me if several stacks accidentally
5789 	 * SACK too far backwards of previously ACKed data. There really aren't
5790 	 * any security implications of bad SACKing unless the target stack
5791 	 * doesn't validate the option length correctly. Someone trying to
5792 	 * spoof into a TCP connection won't bother blindly sending SACK
5793 	 * options anyway.
5794 	 */
5795 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
5796 		if (pf_modulate_sack(pd, th, dst))
5797 			*copyback = 1;
5798 	}
5799 
5800 #define	MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
5801 	if (SEQ_GEQ(src->seqhi, data_end) &&
5802 	    /* Last octet inside other's window space */
5803 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
5804 	    /* Retrans: not more than one window back */
5805 	    (ackskew >= -MAXACKWINDOW) &&
5806 	    /* Acking not more than one reassembled fragment backwards */
5807 	    (ackskew <= (MAXACKWINDOW << sws)) &&
5808 	    /* Acking not more than one window forward */
5809 	    ((tcp_get_flags(th) & TH_RST) == 0 || orig_seq == src->seqlo ||
5810 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo))) {
5811 	    /* Require an exact/+1 sequence match on resets when possible */
5812 
5813 		if (dst->scrub || src->scrub) {
5814 			if (pf_normalize_tcp_stateful(pd, reason, th,
5815 			    *state, src, dst, copyback))
5816 				return (PF_DROP);
5817 		}
5818 
5819 		/* update max window */
5820 		if (src->max_win < win)
5821 			src->max_win = win;
5822 		/* synchronize sequencing */
5823 		if (SEQ_GT(end, src->seqlo))
5824 			src->seqlo = end;
5825 		/* slide the window of what the other end can send */
5826 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
5827 			dst->seqhi = ack + MAX((win << sws), 1);
5828 
5829 		/* update states */
5830 		if (tcp_get_flags(th) & TH_SYN)
5831 			if (src->state < TCPS_SYN_SENT)
5832 				pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5833 		if (tcp_get_flags(th) & TH_FIN)
5834 			if (src->state < TCPS_CLOSING)
5835 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
5836 		if (tcp_get_flags(th) & TH_ACK) {
5837 			if (dst->state == TCPS_SYN_SENT) {
5838 				pf_set_protostate(*state, pdst,
5839 				    TCPS_ESTABLISHED);
5840 				if (src->state == TCPS_ESTABLISHED &&
5841 				    (*state)->src_node != NULL &&
5842 				    pf_src_connlimit(*state)) {
5843 					REASON_SET(reason, PFRES_SRCLIMIT);
5844 					return (PF_DROP);
5845 				}
5846 			} else if (dst->state == TCPS_CLOSING)
5847 				pf_set_protostate(*state, pdst,
5848 				    TCPS_FIN_WAIT_2);
5849 		}
5850 		if (tcp_get_flags(th) & TH_RST)
5851 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5852 
5853 		/* update expire time */
5854 		(*state)->expire = pf_get_uptime();
5855 		if (src->state >= TCPS_FIN_WAIT_2 &&
5856 		    dst->state >= TCPS_FIN_WAIT_2)
5857 			(*state)->timeout = PFTM_TCP_CLOSED;
5858 		else if (src->state >= TCPS_CLOSING &&
5859 		    dst->state >= TCPS_CLOSING)
5860 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
5861 		else if (src->state < TCPS_ESTABLISHED ||
5862 		    dst->state < TCPS_ESTABLISHED)
5863 			(*state)->timeout = PFTM_TCP_OPENING;
5864 		else if (src->state >= TCPS_CLOSING ||
5865 		    dst->state >= TCPS_CLOSING)
5866 			(*state)->timeout = PFTM_TCP_CLOSING;
5867 		else
5868 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
5869 
5870 		/* Fall through to PASS packet */
5871 
5872 	} else if ((dst->state < TCPS_SYN_SENT ||
5873 		dst->state >= TCPS_FIN_WAIT_2 ||
5874 		src->state >= TCPS_FIN_WAIT_2) &&
5875 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) &&
5876 	    /* Within a window forward of the originating packet */
5877 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
5878 	    /* Within a window backward of the originating packet */
5879 
5880 		/*
5881 		 * This currently handles three situations:
5882 		 *  1) Stupid stacks will shotgun SYNs before their peer
5883 		 *     replies.
5884 		 *  2) When PF catches an already established stream (the
5885 		 *     firewall rebooted, the state table was flushed, routes
5886 		 *     changed...)
5887 		 *  3) Packets get funky immediately after the connection
5888 		 *     closes (this should catch Solaris spurious ACK|FINs
5889 		 *     that web servers like to spew after a close)
5890 		 *
5891 		 * This must be a little more careful than the above code
5892 		 * since packet floods will also be caught here. We don't
5893 		 * update the TTL here to mitigate the damage of a packet
5894 		 * flood and so the same code can handle awkward establishment
5895 		 * and a loosened connection close.
5896 		 * In the establishment case, a correct peer response will
5897 		 * validate the connection, go through the normal state code
5898 		 * and keep updating the state TTL.
5899 		 */
5900 
5901 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
5902 			printf("pf: loose state match: ");
5903 			pf_print_state(*state);
5904 			pf_print_flags(tcp_get_flags(th));
5905 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5906 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
5907 			    pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
5908 			    (unsigned long long)(*state)->packets[1],
5909 			    pd->dir == PF_IN ? "in" : "out",
5910 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5911 		}
5912 
5913 		if (dst->scrub || src->scrub) {
5914 			if (pf_normalize_tcp_stateful(pd, reason, th,
5915 			    *state, src, dst, copyback))
5916 				return (PF_DROP);
5917 		}
5918 
5919 		/* update max window */
5920 		if (src->max_win < win)
5921 			src->max_win = win;
5922 		/* synchronize sequencing */
5923 		if (SEQ_GT(end, src->seqlo))
5924 			src->seqlo = end;
5925 		/* slide the window of what the other end can send */
5926 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
5927 			dst->seqhi = ack + MAX((win << sws), 1);
5928 
5929 		/*
5930 		 * Cannot set dst->seqhi here since this could be a shotgunned
5931 		 * SYN and not an already established connection.
5932 		 */
5933 
5934 		if (tcp_get_flags(th) & TH_FIN)
5935 			if (src->state < TCPS_CLOSING)
5936 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
5937 		if (tcp_get_flags(th) & TH_RST)
5938 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5939 
5940 		/* Fall through to PASS packet */
5941 
5942 	} else {
5943 		if ((*state)->dst.state == TCPS_SYN_SENT &&
5944 		    (*state)->src.state == TCPS_SYN_SENT) {
5945 			/* Send RST for state mismatches during handshake */
5946 			if (!(tcp_get_flags(th) & TH_RST))
5947 				pf_send_tcp((*state)->rule, pd->af,
5948 				    pd->dst, pd->src, th->th_dport,
5949 				    th->th_sport, ntohl(th->th_ack), 0,
5950 				    TH_RST, 0, 0,
5951 				    (*state)->rule->return_ttl, M_SKIP_FIREWALL,
5952 				    0, 0, (*state)->act.rtableid);
5953 			src->seqlo = 0;
5954 			src->seqhi = 1;
5955 			src->max_win = 1;
5956 		} else if (V_pf_status.debug >= PF_DEBUG_MISC) {
5957 			printf("pf: BAD state: ");
5958 			pf_print_state(*state);
5959 			pf_print_flags(tcp_get_flags(th));
5960 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5961 			    "pkts=%llu:%llu dir=%s,%s\n",
5962 			    seq, orig_seq, ack, pd->p_len, ackskew,
5963 			    (unsigned long long)(*state)->packets[0],
5964 			    (unsigned long long)(*state)->packets[1],
5965 			    pd->dir == PF_IN ? "in" : "out",
5966 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5967 			printf("pf: State failure on: %c %c %c %c | %c %c\n",
5968 			    SEQ_GEQ(src->seqhi, data_end) ? ' ' : '1',
5969 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
5970 			    ' ': '2',
5971 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
5972 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
5973 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) ?' ' :'5',
5974 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
5975 		}
5976 		REASON_SET(reason, PFRES_BADSTATE);
5977 		return (PF_DROP);
5978 	}
5979 
5980 	return (PF_PASS);
5981 }
5982 
5983 static int
pf_tcp_track_sloppy(struct pf_kstate ** state,struct pf_pdesc * pd,u_short * reason)5984 pf_tcp_track_sloppy(struct pf_kstate **state, struct pf_pdesc *pd, u_short *reason)
5985 {
5986 	struct tcphdr		*th = &pd->hdr.tcp;
5987 	struct pf_state_peer	*src, *dst;
5988 	u_int8_t		 psrc, pdst;
5989 
5990 	if (pd->dir == (*state)->direction) {
5991 		src = &(*state)->src;
5992 		dst = &(*state)->dst;
5993 		psrc = PF_PEER_SRC;
5994 		pdst = PF_PEER_DST;
5995 	} else {
5996 		src = &(*state)->dst;
5997 		dst = &(*state)->src;
5998 		psrc = PF_PEER_DST;
5999 		pdst = PF_PEER_SRC;
6000 	}
6001 
6002 	if (tcp_get_flags(th) & TH_SYN)
6003 		if (src->state < TCPS_SYN_SENT)
6004 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
6005 	if (tcp_get_flags(th) & TH_FIN)
6006 		if (src->state < TCPS_CLOSING)
6007 			pf_set_protostate(*state, psrc, TCPS_CLOSING);
6008 	if (tcp_get_flags(th) & TH_ACK) {
6009 		if (dst->state == TCPS_SYN_SENT) {
6010 			pf_set_protostate(*state, pdst, TCPS_ESTABLISHED);
6011 			if (src->state == TCPS_ESTABLISHED &&
6012 			    (*state)->src_node != NULL &&
6013 			    pf_src_connlimit(*state)) {
6014 				REASON_SET(reason, PFRES_SRCLIMIT);
6015 				return (PF_DROP);
6016 			}
6017 		} else if (dst->state == TCPS_CLOSING) {
6018 			pf_set_protostate(*state, pdst, TCPS_FIN_WAIT_2);
6019 		} else if (src->state == TCPS_SYN_SENT &&
6020 		    dst->state < TCPS_SYN_SENT) {
6021 			/*
6022 			 * Handle a special sloppy case where we only see one
6023 			 * half of the connection. If there is a ACK after
6024 			 * the initial SYN without ever seeing a packet from
6025 			 * the destination, set the connection to established.
6026 			 */
6027 			pf_set_protostate(*state, PF_PEER_BOTH,
6028 			    TCPS_ESTABLISHED);
6029 			dst->state = src->state = TCPS_ESTABLISHED;
6030 			if ((*state)->src_node != NULL &&
6031 			    pf_src_connlimit(*state)) {
6032 				REASON_SET(reason, PFRES_SRCLIMIT);
6033 				return (PF_DROP);
6034 			}
6035 		} else if (src->state == TCPS_CLOSING &&
6036 		    dst->state == TCPS_ESTABLISHED &&
6037 		    dst->seqlo == 0) {
6038 			/*
6039 			 * Handle the closing of half connections where we
6040 			 * don't see the full bidirectional FIN/ACK+ACK
6041 			 * handshake.
6042 			 */
6043 			pf_set_protostate(*state, pdst, TCPS_CLOSING);
6044 		}
6045 	}
6046 	if (tcp_get_flags(th) & TH_RST)
6047 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
6048 
6049 	/* update expire time */
6050 	(*state)->expire = pf_get_uptime();
6051 	if (src->state >= TCPS_FIN_WAIT_2 &&
6052 	    dst->state >= TCPS_FIN_WAIT_2)
6053 		(*state)->timeout = PFTM_TCP_CLOSED;
6054 	else if (src->state >= TCPS_CLOSING &&
6055 	    dst->state >= TCPS_CLOSING)
6056 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
6057 	else if (src->state < TCPS_ESTABLISHED ||
6058 	    dst->state < TCPS_ESTABLISHED)
6059 		(*state)->timeout = PFTM_TCP_OPENING;
6060 	else if (src->state >= TCPS_CLOSING ||
6061 	    dst->state >= TCPS_CLOSING)
6062 		(*state)->timeout = PFTM_TCP_CLOSING;
6063 	else
6064 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
6065 
6066 	return (PF_PASS);
6067 }
6068 
6069 static int
pf_synproxy(struct pf_pdesc * pd,struct pf_kstate ** state,u_short * reason)6070 pf_synproxy(struct pf_pdesc *pd, struct pf_kstate **state, u_short *reason)
6071 {
6072 	struct pf_state_key	*sk = (*state)->key[pd->didx];
6073 	struct tcphdr		*th = &pd->hdr.tcp;
6074 
6075 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
6076 		if (pd->dir != (*state)->direction) {
6077 			REASON_SET(reason, PFRES_SYNPROXY);
6078 			return (PF_SYNPROXY_DROP);
6079 		}
6080 		if (tcp_get_flags(th) & TH_SYN) {
6081 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
6082 				REASON_SET(reason, PFRES_SYNPROXY);
6083 				return (PF_DROP);
6084 			}
6085 			pf_send_tcp((*state)->rule, pd->af, pd->dst,
6086 			    pd->src, th->th_dport, th->th_sport,
6087 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
6088 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0,
6089 			    M_SKIP_FIREWALL, 0, 0, (*state)->act.rtableid);
6090 			REASON_SET(reason, PFRES_SYNPROXY);
6091 			return (PF_SYNPROXY_DROP);
6092 		} else if ((tcp_get_flags(th) & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
6093 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
6094 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
6095 			REASON_SET(reason, PFRES_SYNPROXY);
6096 			return (PF_DROP);
6097 		} else if ((*state)->src_node != NULL &&
6098 		    pf_src_connlimit(*state)) {
6099 			REASON_SET(reason, PFRES_SRCLIMIT);
6100 			return (PF_DROP);
6101 		} else
6102 			pf_set_protostate(*state, PF_PEER_SRC,
6103 			    PF_TCPS_PROXY_DST);
6104 	}
6105 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
6106 		if (pd->dir == (*state)->direction) {
6107 			if (((tcp_get_flags(th) & (TH_SYN|TH_ACK)) != TH_ACK) ||
6108 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
6109 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
6110 				REASON_SET(reason, PFRES_SYNPROXY);
6111 				return (PF_DROP);
6112 			}
6113 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
6114 			if ((*state)->dst.seqhi == 1)
6115 				(*state)->dst.seqhi = htonl(arc4random());
6116 			pf_send_tcp((*state)->rule, pd->af,
6117 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
6118 			    sk->port[pd->sidx], sk->port[pd->didx],
6119 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
6120 			    (*state)->src.mss, 0,
6121 			    (*state)->orig_kif->pfik_ifp == V_loif ? M_LOOP : 0,
6122 			    (*state)->tag, 0, (*state)->act.rtableid);
6123 			REASON_SET(reason, PFRES_SYNPROXY);
6124 			return (PF_SYNPROXY_DROP);
6125 		} else if (((tcp_get_flags(th) & (TH_SYN|TH_ACK)) !=
6126 		    (TH_SYN|TH_ACK)) ||
6127 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
6128 			REASON_SET(reason, PFRES_SYNPROXY);
6129 			return (PF_DROP);
6130 		} else {
6131 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
6132 			(*state)->dst.seqlo = ntohl(th->th_seq);
6133 			pf_send_tcp((*state)->rule, pd->af, pd->dst,
6134 			    pd->src, th->th_dport, th->th_sport,
6135 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
6136 			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
6137 			    (*state)->tag, 0, (*state)->act.rtableid);
6138 			pf_send_tcp((*state)->rule, pd->af,
6139 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
6140 			    sk->port[pd->sidx], sk->port[pd->didx],
6141 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
6142 			    TH_ACK, (*state)->dst.max_win, 0, 0,
6143 			    M_SKIP_FIREWALL, 0, 0, (*state)->act.rtableid);
6144 			(*state)->src.seqdiff = (*state)->dst.seqhi -
6145 			    (*state)->src.seqlo;
6146 			(*state)->dst.seqdiff = (*state)->src.seqhi -
6147 			    (*state)->dst.seqlo;
6148 			(*state)->src.seqhi = (*state)->src.seqlo +
6149 			    (*state)->dst.max_win;
6150 			(*state)->dst.seqhi = (*state)->dst.seqlo +
6151 			    (*state)->src.max_win;
6152 			(*state)->src.wscale = (*state)->dst.wscale = 0;
6153 			pf_set_protostate(*state, PF_PEER_BOTH,
6154 			    TCPS_ESTABLISHED);
6155 			REASON_SET(reason, PFRES_SYNPROXY);
6156 			return (PF_SYNPROXY_DROP);
6157 		}
6158 	}
6159 
6160 	return (PF_PASS);
6161 }
6162 
6163 static int
pf_test_state_tcp(struct pf_kstate ** state,struct pf_pdesc * pd,u_short * reason)6164 pf_test_state_tcp(struct pf_kstate **state, struct pf_pdesc *pd,
6165     u_short *reason)
6166 {
6167 	struct pf_state_key_cmp	 key;
6168 	struct tcphdr		*th = &pd->hdr.tcp;
6169 	int			 copyback = 0;
6170 	int			 action;
6171 	struct pf_state_peer	*src, *dst;
6172 
6173 	bzero(&key, sizeof(key));
6174 	key.af = pd->af;
6175 	key.proto = IPPROTO_TCP;
6176 	if (pd->dir == PF_IN)	{	/* wire side, straight */
6177 		PF_ACPY(&key.addr[0], pd->src, key.af);
6178 		PF_ACPY(&key.addr[1], pd->dst, key.af);
6179 		key.port[0] = th->th_sport;
6180 		key.port[1] = th->th_dport;
6181 	} else {			/* stack side, reverse */
6182 		PF_ACPY(&key.addr[1], pd->src, key.af);
6183 		PF_ACPY(&key.addr[0], pd->dst, key.af);
6184 		key.port[1] = th->th_sport;
6185 		key.port[0] = th->th_dport;
6186 	}
6187 
6188 	STATE_LOOKUP(&key, *state, pd);
6189 
6190 	if (pd->dir == (*state)->direction) {
6191 		src = &(*state)->src;
6192 		dst = &(*state)->dst;
6193 	} else {
6194 		src = &(*state)->dst;
6195 		dst = &(*state)->src;
6196 	}
6197 
6198 	if ((action = pf_synproxy(pd, state, reason)) != PF_PASS)
6199 		return (action);
6200 
6201 	if (dst->state >= TCPS_FIN_WAIT_2 &&
6202 	    src->state >= TCPS_FIN_WAIT_2 &&
6203 	    (((tcp_get_flags(th) & (TH_SYN|TH_ACK)) == TH_SYN) ||
6204 	    ((tcp_get_flags(th) & (TH_SYN|TH_ACK|TH_RST)) == TH_ACK &&
6205 	    pf_syncookie_check(pd) && pd->dir == PF_IN))) {
6206 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
6207 			printf("pf: state reuse ");
6208 			pf_print_state(*state);
6209 			pf_print_flags(tcp_get_flags(th));
6210 			printf("\n");
6211 		}
6212 		/* XXX make sure it's the same direction ?? */
6213 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_CLOSED);
6214 		pf_unlink_state(*state);
6215 		*state = NULL;
6216 		return (PF_DROP);
6217 	}
6218 
6219 	if ((*state)->state_flags & PFSTATE_SLOPPY) {
6220 		if (pf_tcp_track_sloppy(state, pd, reason) == PF_DROP)
6221 			return (PF_DROP);
6222 	} else {
6223 		if (pf_tcp_track_full(state, pd, reason,
6224 		    &copyback) == PF_DROP)
6225 			return (PF_DROP);
6226 	}
6227 
6228 	/* translate source/destination address, if necessary */
6229 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6230 		struct pf_state_key *nk = (*state)->key[pd->didx];
6231 
6232 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
6233 		    nk->port[pd->sidx] != th->th_sport)
6234 			pf_change_ap(pd->m, pd->src, &th->th_sport,
6235 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
6236 			    nk->port[pd->sidx], 0, pd->af);
6237 
6238 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
6239 		    nk->port[pd->didx] != th->th_dport)
6240 			pf_change_ap(pd->m, pd->dst, &th->th_dport,
6241 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
6242 			    nk->port[pd->didx], 0, pd->af);
6243 		copyback = 1;
6244 	}
6245 
6246 	/* Copyback sequence modulation or stateful scrub changes if needed */
6247 	if (copyback)
6248 		m_copyback(pd->m, pd->off, sizeof(*th), (caddr_t)th);
6249 
6250 	return (PF_PASS);
6251 }
6252 
6253 static int
pf_test_state_udp(struct pf_kstate ** state,struct pf_pdesc * pd)6254 pf_test_state_udp(struct pf_kstate **state, struct pf_pdesc *pd)
6255 {
6256 	struct pf_state_peer	*src, *dst;
6257 	struct pf_state_key_cmp	 key;
6258 	struct udphdr		*uh = &pd->hdr.udp;
6259 	uint8_t			 psrc, pdst;
6260 
6261 	bzero(&key, sizeof(key));
6262 	key.af = pd->af;
6263 	key.proto = IPPROTO_UDP;
6264 	if (pd->dir == PF_IN)	{	/* wire side, straight */
6265 		PF_ACPY(&key.addr[0], pd->src, key.af);
6266 		PF_ACPY(&key.addr[1], pd->dst, key.af);
6267 		key.port[0] = uh->uh_sport;
6268 		key.port[1] = uh->uh_dport;
6269 	} else {			/* stack side, reverse */
6270 		PF_ACPY(&key.addr[1], pd->src, key.af);
6271 		PF_ACPY(&key.addr[0], pd->dst, key.af);
6272 		key.port[1] = uh->uh_sport;
6273 		key.port[0] = uh->uh_dport;
6274 	}
6275 
6276 	STATE_LOOKUP(&key, *state, pd);
6277 
6278 	if (pd->dir == (*state)->direction) {
6279 		src = &(*state)->src;
6280 		dst = &(*state)->dst;
6281 		psrc = PF_PEER_SRC;
6282 		pdst = PF_PEER_DST;
6283 	} else {
6284 		src = &(*state)->dst;
6285 		dst = &(*state)->src;
6286 		psrc = PF_PEER_DST;
6287 		pdst = PF_PEER_SRC;
6288 	}
6289 
6290 	/* update states */
6291 	if (src->state < PFUDPS_SINGLE)
6292 		pf_set_protostate(*state, psrc, PFUDPS_SINGLE);
6293 	if (dst->state == PFUDPS_SINGLE)
6294 		pf_set_protostate(*state, pdst, PFUDPS_MULTIPLE);
6295 
6296 	/* update expire time */
6297 	(*state)->expire = pf_get_uptime();
6298 	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
6299 		(*state)->timeout = PFTM_UDP_MULTIPLE;
6300 	else
6301 		(*state)->timeout = PFTM_UDP_SINGLE;
6302 
6303 	/* translate source/destination address, if necessary */
6304 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6305 		struct pf_state_key *nk = (*state)->key[pd->didx];
6306 
6307 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
6308 		    nk->port[pd->sidx] != uh->uh_sport)
6309 			pf_change_ap(pd->m, pd->src, &uh->uh_sport, pd->ip_sum,
6310 			    &uh->uh_sum, &nk->addr[pd->sidx],
6311 			    nk->port[pd->sidx], 1, pd->af);
6312 
6313 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
6314 		    nk->port[pd->didx] != uh->uh_dport)
6315 			pf_change_ap(pd->m, pd->dst, &uh->uh_dport, pd->ip_sum,
6316 			    &uh->uh_sum, &nk->addr[pd->didx],
6317 			    nk->port[pd->didx], 1, pd->af);
6318 		m_copyback(pd->m, pd->off, sizeof(*uh), (caddr_t)uh);
6319 	}
6320 
6321 	return (PF_PASS);
6322 }
6323 
6324 static int
pf_test_state_sctp(struct pf_kstate ** state,struct pf_pdesc * pd,u_short * reason)6325 pf_test_state_sctp(struct pf_kstate **state, struct pf_pdesc *pd,
6326     u_short *reason)
6327 {
6328 	struct pf_state_key_cmp	 key;
6329 	struct pf_state_peer	*src, *dst;
6330 	struct sctphdr		*sh = &pd->hdr.sctp;
6331 	u_int8_t		 psrc; //, pdst;
6332 
6333 	bzero(&key, sizeof(key));
6334 	key.af = pd->af;
6335 	key.proto = IPPROTO_SCTP;
6336 	if (pd->dir == PF_IN)	{	/* wire side, straight */
6337 		PF_ACPY(&key.addr[0], pd->src, key.af);
6338 		PF_ACPY(&key.addr[1], pd->dst, key.af);
6339 		key.port[0] = sh->src_port;
6340 		key.port[1] = sh->dest_port;
6341 	} else {			/* stack side, reverse */
6342 		PF_ACPY(&key.addr[1], pd->src, key.af);
6343 		PF_ACPY(&key.addr[0], pd->dst, key.af);
6344 		key.port[1] = sh->src_port;
6345 		key.port[0] = sh->dest_port;
6346 	}
6347 
6348 	STATE_LOOKUP(&key, *state, pd);
6349 
6350 	if (pd->dir == (*state)->direction) {
6351 		src = &(*state)->src;
6352 		dst = &(*state)->dst;
6353 		psrc = PF_PEER_SRC;
6354 	} else {
6355 		src = &(*state)->dst;
6356 		dst = &(*state)->src;
6357 		psrc = PF_PEER_DST;
6358 	}
6359 
6360 	if ((src->state >= SCTP_SHUTDOWN_SENT || src->state == SCTP_CLOSED) &&
6361 	    (dst->state >= SCTP_SHUTDOWN_SENT || dst->state == SCTP_CLOSED) &&
6362 	    pd->sctp_flags & PFDESC_SCTP_INIT) {
6363 		pf_set_protostate(*state, PF_PEER_BOTH, SCTP_CLOSED);
6364 		pf_unlink_state(*state);
6365 		*state = NULL;
6366 		return (PF_DROP);
6367 	}
6368 
6369 	/* Track state. */
6370 	if (pd->sctp_flags & PFDESC_SCTP_INIT) {
6371 		if (src->state < SCTP_COOKIE_WAIT) {
6372 			pf_set_protostate(*state, psrc, SCTP_COOKIE_WAIT);
6373 			(*state)->timeout = PFTM_SCTP_OPENING;
6374 		}
6375 	}
6376 	if (pd->sctp_flags & PFDESC_SCTP_INIT_ACK) {
6377 		MPASS(dst->scrub != NULL);
6378 		if (dst->scrub->pfss_v_tag == 0)
6379 			dst->scrub->pfss_v_tag = pd->sctp_initiate_tag;
6380 	}
6381 
6382 	if (pd->sctp_flags & (PFDESC_SCTP_COOKIE | PFDESC_SCTP_HEARTBEAT_ACK)) {
6383 		if (src->state < SCTP_ESTABLISHED) {
6384 			pf_set_protostate(*state, psrc, SCTP_ESTABLISHED);
6385 			(*state)->timeout = PFTM_SCTP_ESTABLISHED;
6386 		}
6387 	}
6388 	if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN | PFDESC_SCTP_ABORT |
6389 	    PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
6390 		if (src->state < SCTP_SHUTDOWN_PENDING) {
6391 			pf_set_protostate(*state, psrc, SCTP_SHUTDOWN_PENDING);
6392 			(*state)->timeout = PFTM_SCTP_CLOSING;
6393 		}
6394 	}
6395 	if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
6396 		pf_set_protostate(*state, psrc, SCTP_CLOSED);
6397 		(*state)->timeout = PFTM_SCTP_CLOSED;
6398 	}
6399 
6400 	if (src->scrub != NULL) {
6401 		if (src->scrub->pfss_v_tag == 0) {
6402 			src->scrub->pfss_v_tag = pd->hdr.sctp.v_tag;
6403 		} else  if (src->scrub->pfss_v_tag != pd->hdr.sctp.v_tag)
6404 			return (PF_DROP);
6405 	}
6406 
6407 	(*state)->expire = pf_get_uptime();
6408 
6409 	/* translate source/destination address, if necessary */
6410 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6411 		uint16_t checksum = 0;
6412 		struct pf_state_key *nk = (*state)->key[pd->didx];
6413 
6414 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
6415 		    nk->port[pd->sidx] != pd->hdr.sctp.src_port) {
6416 			pf_change_ap(pd->m, pd->src, &pd->hdr.sctp.src_port,
6417 			    pd->ip_sum, &checksum, &nk->addr[pd->sidx],
6418 			    nk->port[pd->sidx], 1, pd->af);
6419 		}
6420 
6421 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
6422 		    nk->port[pd->didx] != pd->hdr.sctp.dest_port) {
6423 			pf_change_ap(pd->m, pd->dst, &pd->hdr.sctp.dest_port,
6424 			    pd->ip_sum, &checksum, &nk->addr[pd->didx],
6425 			    nk->port[pd->didx], 1, pd->af);
6426 		}
6427 	}
6428 
6429 	return (PF_PASS);
6430 }
6431 
6432 static void
pf_sctp_multihome_detach_addr(const struct pf_kstate * s)6433 pf_sctp_multihome_detach_addr(const struct pf_kstate *s)
6434 {
6435 	struct pf_sctp_endpoint key;
6436 	struct pf_sctp_endpoint *ep;
6437 	struct pf_state_key *sks = s->key[PF_SK_STACK];
6438 	struct pf_sctp_source *i, *tmp;
6439 
6440 	if (sks == NULL || sks->proto != IPPROTO_SCTP || s->dst.scrub == NULL)
6441 		return;
6442 
6443 	PF_SCTP_ENDPOINTS_LOCK();
6444 
6445 	key.v_tag = s->dst.scrub->pfss_v_tag;
6446 	ep  = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6447 	if (ep != NULL) {
6448 		TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
6449 			if (pf_addr_cmp(&i->addr,
6450 			    &s->key[PF_SK_WIRE]->addr[s->direction == PF_OUT],
6451 			    s->key[PF_SK_WIRE]->af) == 0) {
6452 				SDT_PROBE3(pf, sctp, multihome, remove,
6453 				    key.v_tag, s, i);
6454 				TAILQ_REMOVE(&ep->sources, i, entry);
6455 				free(i, M_PFTEMP);
6456 				break;
6457 			}
6458 		}
6459 
6460 		if (TAILQ_EMPTY(&ep->sources)) {
6461 			RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6462 			free(ep, M_PFTEMP);
6463 		}
6464 	}
6465 
6466 	/* Other direction. */
6467 	key.v_tag = s->src.scrub->pfss_v_tag;
6468 	ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6469 	if (ep != NULL) {
6470 		TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
6471 			if (pf_addr_cmp(&i->addr,
6472 			    &s->key[PF_SK_WIRE]->addr[s->direction == PF_IN],
6473 			    s->key[PF_SK_WIRE]->af) == 0) {
6474 				SDT_PROBE3(pf, sctp, multihome, remove,
6475 				    key.v_tag, s, i);
6476 				TAILQ_REMOVE(&ep->sources, i, entry);
6477 				free(i, M_PFTEMP);
6478 				break;
6479 			}
6480 		}
6481 
6482 		if (TAILQ_EMPTY(&ep->sources)) {
6483 			RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6484 			free(ep, M_PFTEMP);
6485 		}
6486 	}
6487 
6488 	PF_SCTP_ENDPOINTS_UNLOCK();
6489 }
6490 
6491 static void
pf_sctp_multihome_add_addr(struct pf_pdesc * pd,struct pf_addr * a,uint32_t v_tag)6492 pf_sctp_multihome_add_addr(struct pf_pdesc *pd, struct pf_addr *a, uint32_t v_tag)
6493 {
6494 	struct pf_sctp_endpoint key = {
6495 		.v_tag = v_tag,
6496 	};
6497 	struct pf_sctp_source *i;
6498 	struct pf_sctp_endpoint *ep;
6499 
6500 	PF_SCTP_ENDPOINTS_LOCK();
6501 
6502 	ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6503 	if (ep == NULL) {
6504 		ep = malloc(sizeof(struct pf_sctp_endpoint),
6505 		    M_PFTEMP, M_NOWAIT);
6506 		if (ep == NULL) {
6507 			PF_SCTP_ENDPOINTS_UNLOCK();
6508 			return;
6509 		}
6510 
6511 		ep->v_tag = v_tag;
6512 		TAILQ_INIT(&ep->sources);
6513 		RB_INSERT(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6514 	}
6515 
6516 	/* Avoid inserting duplicates. */
6517 	TAILQ_FOREACH(i, &ep->sources, entry) {
6518 		if (pf_addr_cmp(&i->addr, a, pd->af) == 0) {
6519 			PF_SCTP_ENDPOINTS_UNLOCK();
6520 			return;
6521 		}
6522 	}
6523 
6524 	i = malloc(sizeof(*i), M_PFTEMP, M_NOWAIT);
6525 	if (i == NULL) {
6526 		PF_SCTP_ENDPOINTS_UNLOCK();
6527 		return;
6528 	}
6529 
6530 	i->af = pd->af;
6531 	memcpy(&i->addr, a, sizeof(*a));
6532 	TAILQ_INSERT_TAIL(&ep->sources, i, entry);
6533 	SDT_PROBE2(pf, sctp, multihome, add, v_tag, i);
6534 
6535 	PF_SCTP_ENDPOINTS_UNLOCK();
6536 }
6537 
6538 static void
pf_sctp_multihome_delayed(struct pf_pdesc * pd,struct pfi_kkif * kif,struct pf_kstate * s,int action)6539 pf_sctp_multihome_delayed(struct pf_pdesc *pd, struct pfi_kkif *kif,
6540     struct pf_kstate *s, int action)
6541 {
6542 	struct pf_sctp_multihome_job	*j, *tmp;
6543 	struct pf_sctp_source		*i;
6544 	int			 ret __unused;
6545 	struct pf_kstate	*sm = NULL;
6546 	struct pf_krule		*ra = NULL;
6547 	struct pf_krule		*r = &V_pf_default_rule;
6548 	struct pf_kruleset	*rs = NULL;
6549 	bool do_extra = true;
6550 
6551 	PF_RULES_RLOCK_TRACKER;
6552 
6553 again:
6554 	TAILQ_FOREACH_SAFE(j, &pd->sctp_multihome_jobs, next, tmp) {
6555 		if (s == NULL || action != PF_PASS)
6556 			goto free;
6557 
6558 		/* Confirm we don't recurse here. */
6559 		MPASS(! (pd->sctp_flags & PFDESC_SCTP_ADD_IP));
6560 
6561 		switch (j->op) {
6562 		case  SCTP_ADD_IP_ADDRESS: {
6563 			uint32_t v_tag = pd->sctp_initiate_tag;
6564 
6565 			if (v_tag == 0) {
6566 				if (s->direction == pd->dir)
6567 					v_tag = s->src.scrub->pfss_v_tag;
6568 				else
6569 					v_tag = s->dst.scrub->pfss_v_tag;
6570 			}
6571 
6572 			/*
6573 			 * Avoid duplicating states. We'll already have
6574 			 * created a state based on the source address of
6575 			 * the packet, but SCTP endpoints may also list this
6576 			 * address again in the INIT(_ACK) parameters.
6577 			 */
6578 			if (pf_addr_cmp(&j->src, pd->src, pd->af) == 0) {
6579 				break;
6580 			}
6581 
6582 			j->pd.sctp_flags |= PFDESC_SCTP_ADD_IP;
6583 			PF_RULES_RLOCK();
6584 			sm = NULL;
6585 			/*
6586 			 * New connections need to be floating, because
6587 			 * we cannot know what interfaces it will use.
6588 			 * That's why we pass V_pfi_all rather than kif.
6589 			 */
6590 			j->pd.kif = V_pfi_all;
6591 			ret = pf_test_rule(&r, &sm,
6592 			    &j->pd, &ra, &rs, NULL);
6593 			PF_RULES_RUNLOCK();
6594 			SDT_PROBE4(pf, sctp, multihome, test, kif, r, j->pd.m, ret);
6595 			if (ret != PF_DROP && sm != NULL) {
6596 				/* Inherit v_tag values. */
6597 				if (sm->direction == s->direction) {
6598 					sm->src.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
6599 					sm->dst.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
6600 				} else {
6601 					sm->src.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
6602 					sm->dst.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
6603 				}
6604 				PF_STATE_UNLOCK(sm);
6605 			} else {
6606 				/* If we try duplicate inserts? */
6607 				break;
6608 			}
6609 
6610 			/* Only add the address if we've actually allowed the state. */
6611 			pf_sctp_multihome_add_addr(pd, &j->src, v_tag);
6612 
6613 			if (! do_extra) {
6614 				break;
6615 			}
6616 			/*
6617 			 * We need to do this for each of our source addresses.
6618 			 * Find those based on the verification tag.
6619 			 */
6620 			struct pf_sctp_endpoint key = {
6621 				.v_tag = pd->hdr.sctp.v_tag,
6622 			};
6623 			struct pf_sctp_endpoint *ep;
6624 
6625 			PF_SCTP_ENDPOINTS_LOCK();
6626 			ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6627 			if (ep == NULL) {
6628 				PF_SCTP_ENDPOINTS_UNLOCK();
6629 				break;
6630 			}
6631 			MPASS(ep != NULL);
6632 
6633 			TAILQ_FOREACH(i, &ep->sources, entry) {
6634 				struct pf_sctp_multihome_job *nj;
6635 
6636 				/* SCTP can intermingle IPv4 and IPv6. */
6637 				if (i->af != pd->af)
6638 					continue;
6639 
6640 				nj = malloc(sizeof(*nj), M_PFTEMP, M_NOWAIT | M_ZERO);
6641 				if (! nj) {
6642 					continue;
6643 				}
6644 				memcpy(&nj->pd, &j->pd, sizeof(j->pd));
6645 				memcpy(&nj->src, &j->src, sizeof(nj->src));
6646 				nj->pd.src = &nj->src;
6647 				// New destination address!
6648 				memcpy(&nj->dst, &i->addr, sizeof(nj->dst));
6649 				nj->pd.dst = &nj->dst;
6650 				nj->pd.m = j->pd.m;
6651 				nj->op = j->op;
6652 
6653 				TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, nj, next);
6654 			}
6655 			PF_SCTP_ENDPOINTS_UNLOCK();
6656 
6657 			break;
6658 		}
6659 		case SCTP_DEL_IP_ADDRESS: {
6660 			struct pf_state_key_cmp key;
6661 			uint8_t psrc;
6662 
6663 			bzero(&key, sizeof(key));
6664 			key.af = j->pd.af;
6665 			key.proto = IPPROTO_SCTP;
6666 			if (j->pd.dir == PF_IN)	{	/* wire side, straight */
6667 				PF_ACPY(&key.addr[0], j->pd.src, key.af);
6668 				PF_ACPY(&key.addr[1], j->pd.dst, key.af);
6669 				key.port[0] = j->pd.hdr.sctp.src_port;
6670 				key.port[1] = j->pd.hdr.sctp.dest_port;
6671 			} else {			/* stack side, reverse */
6672 				PF_ACPY(&key.addr[1], j->pd.src, key.af);
6673 				PF_ACPY(&key.addr[0], j->pd.dst, key.af);
6674 				key.port[1] = j->pd.hdr.sctp.src_port;
6675 				key.port[0] = j->pd.hdr.sctp.dest_port;
6676 			}
6677 
6678 			sm = pf_find_state(kif, &key, j->pd.dir);
6679 			if (sm != NULL) {
6680 				PF_STATE_LOCK_ASSERT(sm);
6681 				if (j->pd.dir == sm->direction) {
6682 					psrc = PF_PEER_SRC;
6683 				} else {
6684 					psrc = PF_PEER_DST;
6685 				}
6686 				pf_set_protostate(sm, psrc, SCTP_SHUTDOWN_PENDING);
6687 				sm->timeout = PFTM_SCTP_CLOSING;
6688 				PF_STATE_UNLOCK(sm);
6689 			}
6690 			break;
6691 		default:
6692 			panic("Unknown op %#x", j->op);
6693 		}
6694 	}
6695 
6696 	free:
6697 		TAILQ_REMOVE(&pd->sctp_multihome_jobs, j, next);
6698 		free(j, M_PFTEMP);
6699 	}
6700 
6701 	/* We may have inserted extra work while processing the list. */
6702 	if (! TAILQ_EMPTY(&pd->sctp_multihome_jobs)) {
6703 		do_extra = false;
6704 		goto again;
6705 	}
6706 }
6707 
6708 static int
pf_multihome_scan(int start,int len,struct pf_pdesc * pd,int op)6709 pf_multihome_scan(int start, int len, struct pf_pdesc *pd, int op)
6710 {
6711 	int			 off = 0;
6712 	struct pf_sctp_multihome_job	*job;
6713 
6714 	while (off < len) {
6715 		struct sctp_paramhdr h;
6716 
6717 		if (!pf_pull_hdr(pd->m, start + off, &h, sizeof(h), NULL, NULL,
6718 		    pd->af))
6719 			return (PF_DROP);
6720 
6721 		/* Parameters are at least 4 bytes. */
6722 		if (ntohs(h.param_length) < 4)
6723 			return (PF_DROP);
6724 
6725 		switch (ntohs(h.param_type)) {
6726 		case  SCTP_IPV4_ADDRESS: {
6727 			struct in_addr t;
6728 
6729 			if (ntohs(h.param_length) !=
6730 			    (sizeof(struct sctp_paramhdr) + sizeof(t)))
6731 				return (PF_DROP);
6732 
6733 			if (!pf_pull_hdr(pd->m, start + off + sizeof(h), &t, sizeof(t),
6734 			    NULL, NULL, pd->af))
6735 				return (PF_DROP);
6736 
6737 			if (in_nullhost(t))
6738 				t.s_addr = pd->src->v4.s_addr;
6739 
6740 			/*
6741 			 * We hold the state lock (idhash) here, which means
6742 			 * that we can't acquire the keyhash, or we'll get a
6743 			 * LOR (and potentially double-lock things too). We also
6744 			 * can't release the state lock here, so instead we'll
6745 			 * enqueue this for async handling.
6746 			 * There's a relatively small race here, in that a
6747 			 * packet using the new addresses could arrive already,
6748 			 * but that's just though luck for it.
6749 			 */
6750 			job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
6751 			if (! job)
6752 				return (PF_DROP);
6753 
6754 			memcpy(&job->pd, pd, sizeof(*pd));
6755 
6756 			// New source address!
6757 			memcpy(&job->src, &t, sizeof(t));
6758 			job->pd.src = &job->src;
6759 			memcpy(&job->dst, pd->dst, sizeof(job->dst));
6760 			job->pd.dst = &job->dst;
6761 			job->pd.m = pd->m;
6762 			job->op = op;
6763 
6764 			TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
6765 			break;
6766 		}
6767 #ifdef INET6
6768 		case SCTP_IPV6_ADDRESS: {
6769 			struct in6_addr t;
6770 
6771 			if (ntohs(h.param_length) !=
6772 			    (sizeof(struct sctp_paramhdr) + sizeof(t)))
6773 				return (PF_DROP);
6774 
6775 			if (!pf_pull_hdr(pd->m, start + off + sizeof(h), &t, sizeof(t),
6776 			    NULL, NULL, pd->af))
6777 				return (PF_DROP);
6778 			if (memcmp(&t, &pd->src->v6, sizeof(t)) == 0)
6779 				break;
6780 			if (memcmp(&t, &in6addr_any, sizeof(t)) == 0)
6781 				memcpy(&t, &pd->src->v6, sizeof(t));
6782 
6783 			job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
6784 			if (! job)
6785 				return (PF_DROP);
6786 
6787 			memcpy(&job->pd, pd, sizeof(*pd));
6788 			memcpy(&job->src, &t, sizeof(t));
6789 			job->pd.src = &job->src;
6790 			memcpy(&job->dst, pd->dst, sizeof(job->dst));
6791 			job->pd.dst = &job->dst;
6792 			job->pd.m = pd->m;
6793 			job->op = op;
6794 
6795 			TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
6796 			break;
6797 		}
6798 #endif
6799 		case SCTP_ADD_IP_ADDRESS: {
6800 			int ret;
6801 			struct sctp_asconf_paramhdr ah;
6802 
6803 			if (!pf_pull_hdr(pd->m, start + off, &ah, sizeof(ah),
6804 			    NULL, NULL, pd->af))
6805 				return (PF_DROP);
6806 
6807 			ret = pf_multihome_scan(start + off + sizeof(ah),
6808 			    ntohs(ah.ph.param_length) - sizeof(ah), pd,
6809 			    SCTP_ADD_IP_ADDRESS);
6810 			if (ret != PF_PASS)
6811 				return (ret);
6812 			break;
6813 		}
6814 		case SCTP_DEL_IP_ADDRESS: {
6815 			int ret;
6816 			struct sctp_asconf_paramhdr ah;
6817 
6818 			if (!pf_pull_hdr(pd->m, start + off, &ah, sizeof(ah),
6819 			    NULL, NULL, pd->af))
6820 				return (PF_DROP);
6821 			ret = pf_multihome_scan(start + off + sizeof(ah),
6822 			    ntohs(ah.ph.param_length) - sizeof(ah), pd,
6823 			    SCTP_DEL_IP_ADDRESS);
6824 			if (ret != PF_PASS)
6825 				return (ret);
6826 			break;
6827 		}
6828 		default:
6829 			break;
6830 		}
6831 
6832 		off += roundup(ntohs(h.param_length), 4);
6833 	}
6834 
6835 	return (PF_PASS);
6836 }
6837 int
pf_multihome_scan_init(int start,int len,struct pf_pdesc * pd)6838 pf_multihome_scan_init(int start, int len, struct pf_pdesc *pd)
6839 {
6840 	start += sizeof(struct sctp_init_chunk);
6841 	len -= sizeof(struct sctp_init_chunk);
6842 
6843 	return (pf_multihome_scan(start, len, pd, SCTP_ADD_IP_ADDRESS));
6844 }
6845 
6846 int
pf_multihome_scan_asconf(int start,int len,struct pf_pdesc * pd)6847 pf_multihome_scan_asconf(int start, int len, struct pf_pdesc *pd)
6848 {
6849 	start += sizeof(struct sctp_asconf_chunk);
6850 	len -= sizeof(struct sctp_asconf_chunk);
6851 
6852 	return (pf_multihome_scan(start, len, pd, SCTP_ADD_IP_ADDRESS));
6853 }
6854 
6855 int
pf_icmp_state_lookup(struct pf_state_key_cmp * key,struct pf_pdesc * pd,struct pf_kstate ** state,int direction,u_int16_t icmpid,u_int16_t type,int icmp_dir,int * iidx,int multi,int inner)6856 pf_icmp_state_lookup(struct pf_state_key_cmp *key, struct pf_pdesc *pd,
6857     struct pf_kstate **state, int direction,
6858     u_int16_t icmpid, u_int16_t type, int icmp_dir,
6859     int *iidx, int multi, int inner)
6860 {
6861 	key->af = pd->af;
6862 	key->proto = pd->proto;
6863 	if (icmp_dir == PF_IN) {
6864 		*iidx = pd->sidx;
6865 		key->port[pd->sidx] = icmpid;
6866 		key->port[pd->didx] = type;
6867 	} else {
6868 		*iidx = pd->didx;
6869 		key->port[pd->sidx] = type;
6870 		key->port[pd->didx] = icmpid;
6871 	}
6872 	if (pf_state_key_addr_setup(pd, key, multi))
6873 		return (PF_DROP);
6874 
6875 	STATE_LOOKUP(key, *state, pd);
6876 
6877 	if ((*state)->state_flags & PFSTATE_SLOPPY)
6878 		return (-1);
6879 
6880 	/* Is this ICMP message flowing in right direction? */
6881 	if ((*state)->rule->type &&
6882 	    (((!inner && (*state)->direction == direction) ||
6883 	    (inner && (*state)->direction != direction)) ?
6884 	    PF_IN : PF_OUT) != icmp_dir) {
6885 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
6886 			printf("pf: icmp type %d in wrong direction (%d): ",
6887 			    ntohs(type), icmp_dir);
6888 			pf_print_state(*state);
6889 			printf("\n");
6890 		}
6891 		PF_STATE_UNLOCK(*state);
6892 		*state = NULL;
6893 		return (PF_DROP);
6894 	}
6895 	return (-1);
6896 }
6897 
6898 static int
pf_test_state_icmp(struct pf_kstate ** state,struct pf_pdesc * pd,u_short * reason)6899 pf_test_state_icmp(struct pf_kstate **state, struct pf_pdesc *pd,
6900     u_short *reason)
6901 {
6902 	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
6903 	u_int16_t	*icmpsum, virtual_id, virtual_type;
6904 	u_int8_t	 icmptype, icmpcode;
6905 	int		 icmp_dir, iidx, ret, multi;
6906 	struct pf_state_key_cmp key;
6907 #ifdef INET
6908 	u_int16_t	 icmpid;
6909 #endif
6910 
6911 	MPASS(*state == NULL);
6912 
6913 	bzero(&key, sizeof(key));
6914 	switch (pd->proto) {
6915 #ifdef INET
6916 	case IPPROTO_ICMP:
6917 		icmptype = pd->hdr.icmp.icmp_type;
6918 		icmpcode = pd->hdr.icmp.icmp_code;
6919 		icmpid = pd->hdr.icmp.icmp_id;
6920 		icmpsum = &pd->hdr.icmp.icmp_cksum;
6921 		break;
6922 #endif /* INET */
6923 #ifdef INET6
6924 	case IPPROTO_ICMPV6:
6925 		icmptype = pd->hdr.icmp6.icmp6_type;
6926 		icmpcode = pd->hdr.icmp6.icmp6_code;
6927 #ifdef INET
6928 		icmpid = pd->hdr.icmp6.icmp6_id;
6929 #endif
6930 		icmpsum = &pd->hdr.icmp6.icmp6_cksum;
6931 		break;
6932 #endif /* INET6 */
6933 	}
6934 
6935 	if (pf_icmp_mapping(pd, icmptype, &icmp_dir, &multi,
6936 	    &virtual_id, &virtual_type) == 0) {
6937 		/*
6938 		 * ICMP query/reply message not related to a TCP/UDP packet.
6939 		 * Search for an ICMP state.
6940 		 */
6941 		ret = pf_icmp_state_lookup(&key, pd, state, pd->dir,
6942 		    virtual_id, virtual_type, icmp_dir, &iidx,
6943 		    PF_ICMP_MULTI_NONE, 0);
6944 		if (ret >= 0) {
6945 			MPASS(*state == NULL);
6946 			if (ret == PF_DROP && pd->af == AF_INET6 &&
6947 			    icmp_dir == PF_OUT) {
6948 				ret = pf_icmp_state_lookup(&key, pd, state,
6949 				    pd->dir, virtual_id, virtual_type,
6950 				    icmp_dir, &iidx, multi, 0);
6951 				if (ret >= 0) {
6952 					MPASS(*state == NULL);
6953 					return (ret);
6954 				}
6955 			} else
6956 				return (ret);
6957 		}
6958 
6959 		(*state)->expire = pf_get_uptime();
6960 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
6961 
6962 		/* translate source/destination address, if necessary */
6963 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6964 			struct pf_state_key *nk = (*state)->key[pd->didx];
6965 
6966 			switch (pd->af) {
6967 #ifdef INET
6968 			case AF_INET:
6969 				if (PF_ANEQ(pd->src,
6970 				    &nk->addr[pd->sidx], AF_INET))
6971 					pf_change_a(&saddr->v4.s_addr,
6972 					    pd->ip_sum,
6973 					    nk->addr[pd->sidx].v4.s_addr, 0);
6974 
6975 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
6976 				    AF_INET))
6977 					pf_change_a(&daddr->v4.s_addr,
6978 					    pd->ip_sum,
6979 					    nk->addr[pd->didx].v4.s_addr, 0);
6980 
6981 				if (nk->port[iidx] !=
6982 				    pd->hdr.icmp.icmp_id) {
6983 					pd->hdr.icmp.icmp_cksum =
6984 					    pf_cksum_fixup(
6985 					    pd->hdr.icmp.icmp_cksum, icmpid,
6986 					    nk->port[iidx], 0);
6987 					pd->hdr.icmp.icmp_id =
6988 					    nk->port[iidx];
6989 				}
6990 
6991 				m_copyback(pd->m, pd->off, ICMP_MINLEN,
6992 				    (caddr_t )&pd->hdr.icmp);
6993 				break;
6994 #endif /* INET */
6995 #ifdef INET6
6996 			case AF_INET6:
6997 				if (PF_ANEQ(pd->src,
6998 				    &nk->addr[pd->sidx], AF_INET6))
6999 					pf_change_a6(saddr,
7000 					    &pd->hdr.icmp6.icmp6_cksum,
7001 					    &nk->addr[pd->sidx], 0);
7002 
7003 				if (PF_ANEQ(pd->dst,
7004 				    &nk->addr[pd->didx], AF_INET6))
7005 					pf_change_a6(daddr,
7006 					    &pd->hdr.icmp6.icmp6_cksum,
7007 					    &nk->addr[pd->didx], 0);
7008 
7009 				m_copyback(pd->m, pd->off, sizeof(struct icmp6_hdr),
7010 				    (caddr_t )&pd->hdr.icmp6);
7011 				break;
7012 #endif /* INET6 */
7013 			}
7014 		}
7015 		return (PF_PASS);
7016 
7017 	} else {
7018 		/*
7019 		 * ICMP error message in response to a TCP/UDP packet.
7020 		 * Extract the inner TCP/UDP header and search for that state.
7021 		 */
7022 
7023 		struct pf_pdesc	pd2;
7024 		bzero(&pd2, sizeof pd2);
7025 #ifdef INET
7026 		struct ip	h2;
7027 #endif /* INET */
7028 #ifdef INET6
7029 		struct ip6_hdr	h2_6;
7030 		int		fragoff2, extoff2;
7031 		u_int32_t	jumbolen;
7032 #endif /* INET6 */
7033 		int		ipoff2 = 0;
7034 
7035 		pd2.af = pd->af;
7036 		pd2.dir = pd->dir;
7037 		/* Payload packet is from the opposite direction. */
7038 		pd2.sidx = (pd->dir == PF_IN) ? 1 : 0;
7039 		pd2.didx = (pd->dir == PF_IN) ? 0 : 1;
7040 		pd2.m = pd->m;
7041 		switch (pd->af) {
7042 #ifdef INET
7043 		case AF_INET:
7044 			/* offset of h2 in mbuf chain */
7045 			ipoff2 = pd->off + ICMP_MINLEN;
7046 
7047 			if (!pf_pull_hdr(pd->m, ipoff2, &h2, sizeof(h2),
7048 			    NULL, reason, pd2.af)) {
7049 				DPFPRINTF(PF_DEBUG_MISC,
7050 				    ("pf: ICMP error message too short "
7051 				    "(ip)\n"));
7052 				return (PF_DROP);
7053 			}
7054 			/*
7055 			 * ICMP error messages don't refer to non-first
7056 			 * fragments
7057 			 */
7058 			if (h2.ip_off & htons(IP_OFFMASK)) {
7059 				REASON_SET(reason, PFRES_FRAG);
7060 				return (PF_DROP);
7061 			}
7062 
7063 			/* offset of protocol header that follows h2 */
7064 			pd2.off = ipoff2 + (h2.ip_hl << 2);
7065 
7066 			pd2.proto = h2.ip_p;
7067 			pd2.src = (struct pf_addr *)&h2.ip_src;
7068 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
7069 			pd2.ip_sum = &h2.ip_sum;
7070 			break;
7071 #endif /* INET */
7072 #ifdef INET6
7073 		case AF_INET6:
7074 			ipoff2 = pd->off + sizeof(struct icmp6_hdr);
7075 
7076 			if (!pf_pull_hdr(pd->m, ipoff2, &h2_6, sizeof(h2_6),
7077 			    NULL, reason, pd2.af)) {
7078 				DPFPRINTF(PF_DEBUG_MISC,
7079 				    ("pf: ICMP error message too short "
7080 				    "(ip6)\n"));
7081 				return (PF_DROP);
7082 			}
7083 			pd2.off = ipoff2;
7084 			if (pf_walk_header6(pd->m, &h2_6, &pd2.off, &extoff2,
7085 				&fragoff2, &pd2.proto, &jumbolen,
7086 				reason) != PF_PASS)
7087 				return (PF_DROP);
7088 
7089 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
7090 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
7091 			pd2.ip_sum = NULL;
7092 			break;
7093 #endif /* INET6 */
7094 		}
7095 
7096 		if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
7097 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
7098 				printf("pf: BAD ICMP %d:%d outer dst: ",
7099 				    icmptype, icmpcode);
7100 				pf_print_host(pd->src, 0, pd->af);
7101 				printf(" -> ");
7102 				pf_print_host(pd->dst, 0, pd->af);
7103 				printf(" inner src: ");
7104 				pf_print_host(pd2.src, 0, pd2.af);
7105 				printf(" -> ");
7106 				pf_print_host(pd2.dst, 0, pd2.af);
7107 				printf("\n");
7108 			}
7109 			REASON_SET(reason, PFRES_BADSTATE);
7110 			return (PF_DROP);
7111 		}
7112 
7113 		switch (pd2.proto) {
7114 		case IPPROTO_TCP: {
7115 			struct tcphdr		 th;
7116 			u_int32_t		 seq;
7117 			struct pf_state_peer	*src, *dst;
7118 			u_int8_t		 dws;
7119 			int			 copyback = 0;
7120 
7121 			/*
7122 			 * Only the first 8 bytes of the TCP header can be
7123 			 * expected. Don't access any TCP header fields after
7124 			 * th_seq, an ackskew test is not possible.
7125 			 */
7126 			if (!pf_pull_hdr(pd->m, pd2.off, &th, 8, NULL, reason,
7127 			    pd2.af)) {
7128 				DPFPRINTF(PF_DEBUG_MISC,
7129 				    ("pf: ICMP error message too short "
7130 				    "(tcp)\n"));
7131 				return (PF_DROP);
7132 			}
7133 
7134 			key.af = pd2.af;
7135 			key.proto = IPPROTO_TCP;
7136 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
7137 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
7138 			key.port[pd2.sidx] = th.th_sport;
7139 			key.port[pd2.didx] = th.th_dport;
7140 
7141 			STATE_LOOKUP(&key, *state, pd);
7142 
7143 			if (pd->dir == (*state)->direction) {
7144 				src = &(*state)->dst;
7145 				dst = &(*state)->src;
7146 			} else {
7147 				src = &(*state)->src;
7148 				dst = &(*state)->dst;
7149 			}
7150 
7151 			if (src->wscale && dst->wscale)
7152 				dws = dst->wscale & PF_WSCALE_MASK;
7153 			else
7154 				dws = 0;
7155 
7156 			/* Demodulate sequence number */
7157 			seq = ntohl(th.th_seq) - src->seqdiff;
7158 			if (src->seqdiff) {
7159 				pf_change_a(&th.th_seq, icmpsum,
7160 				    htonl(seq), 0);
7161 				copyback = 1;
7162 			}
7163 
7164 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
7165 			    (!SEQ_GEQ(src->seqhi, seq) ||
7166 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
7167 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
7168 					printf("pf: BAD ICMP %d:%d ",
7169 					    icmptype, icmpcode);
7170 					pf_print_host(pd->src, 0, pd->af);
7171 					printf(" -> ");
7172 					pf_print_host(pd->dst, 0, pd->af);
7173 					printf(" state: ");
7174 					pf_print_state(*state);
7175 					printf(" seq=%u\n", seq);
7176 				}
7177 				REASON_SET(reason, PFRES_BADSTATE);
7178 				return (PF_DROP);
7179 			} else {
7180 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
7181 					printf("pf: OK ICMP %d:%d ",
7182 					    icmptype, icmpcode);
7183 					pf_print_host(pd->src, 0, pd->af);
7184 					printf(" -> ");
7185 					pf_print_host(pd->dst, 0, pd->af);
7186 					printf(" state: ");
7187 					pf_print_state(*state);
7188 					printf(" seq=%u\n", seq);
7189 				}
7190 			}
7191 
7192 			/* translate source/destination address, if necessary */
7193 			if ((*state)->key[PF_SK_WIRE] !=
7194 			    (*state)->key[PF_SK_STACK]) {
7195 				struct pf_state_key *nk =
7196 				    (*state)->key[pd->didx];
7197 
7198 				if (PF_ANEQ(pd2.src,
7199 				    &nk->addr[pd2.sidx], pd2.af) ||
7200 				    nk->port[pd2.sidx] != th.th_sport)
7201 					pf_change_icmp(pd2.src, &th.th_sport,
7202 					    daddr, &nk->addr[pd2.sidx],
7203 					    nk->port[pd2.sidx], NULL,
7204 					    pd2.ip_sum, icmpsum,
7205 					    pd->ip_sum, 0, pd2.af);
7206 
7207 				if (PF_ANEQ(pd2.dst,
7208 				    &nk->addr[pd2.didx], pd2.af) ||
7209 				    nk->port[pd2.didx] != th.th_dport)
7210 					pf_change_icmp(pd2.dst, &th.th_dport,
7211 					    saddr, &nk->addr[pd2.didx],
7212 					    nk->port[pd2.didx], NULL,
7213 					    pd2.ip_sum, icmpsum,
7214 					    pd->ip_sum, 0, pd2.af);
7215 				copyback = 1;
7216 			}
7217 
7218 			if (copyback) {
7219 				switch (pd2.af) {
7220 #ifdef INET
7221 				case AF_INET:
7222 					m_copyback(pd->m, pd->off, ICMP_MINLEN,
7223 					    (caddr_t )&pd->hdr.icmp);
7224 					m_copyback(pd->m, ipoff2, sizeof(h2),
7225 					    (caddr_t )&h2);
7226 					break;
7227 #endif /* INET */
7228 #ifdef INET6
7229 				case AF_INET6:
7230 					m_copyback(pd->m, pd->off,
7231 					    sizeof(struct icmp6_hdr),
7232 					    (caddr_t )&pd->hdr.icmp6);
7233 					m_copyback(pd->m, ipoff2, sizeof(h2_6),
7234 					    (caddr_t )&h2_6);
7235 					break;
7236 #endif /* INET6 */
7237 				}
7238 				m_copyback(pd->m, pd2.off, 8, (caddr_t)&th);
7239 			}
7240 
7241 			return (PF_PASS);
7242 			break;
7243 		}
7244 		case IPPROTO_UDP: {
7245 			struct udphdr		uh;
7246 
7247 			if (!pf_pull_hdr(pd->m, pd2.off, &uh, sizeof(uh),
7248 			    NULL, reason, pd2.af)) {
7249 				DPFPRINTF(PF_DEBUG_MISC,
7250 				    ("pf: ICMP error message too short "
7251 				    "(udp)\n"));
7252 				return (PF_DROP);
7253 			}
7254 
7255 			key.af = pd2.af;
7256 			key.proto = IPPROTO_UDP;
7257 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
7258 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
7259 			key.port[pd2.sidx] = uh.uh_sport;
7260 			key.port[pd2.didx] = uh.uh_dport;
7261 
7262 			STATE_LOOKUP(&key, *state, pd);
7263 
7264 			/* translate source/destination address, if necessary */
7265 			if ((*state)->key[PF_SK_WIRE] !=
7266 			    (*state)->key[PF_SK_STACK]) {
7267 				struct pf_state_key *nk =
7268 				    (*state)->key[pd->didx];
7269 
7270 				if (PF_ANEQ(pd2.src,
7271 				    &nk->addr[pd2.sidx], pd2.af) ||
7272 				    nk->port[pd2.sidx] != uh.uh_sport)
7273 					pf_change_icmp(pd2.src, &uh.uh_sport,
7274 					    daddr, &nk->addr[pd2.sidx],
7275 					    nk->port[pd2.sidx], &uh.uh_sum,
7276 					    pd2.ip_sum, icmpsum,
7277 					    pd->ip_sum, 1, pd2.af);
7278 
7279 				if (PF_ANEQ(pd2.dst,
7280 				    &nk->addr[pd2.didx], pd2.af) ||
7281 				    nk->port[pd2.didx] != uh.uh_dport)
7282 					pf_change_icmp(pd2.dst, &uh.uh_dport,
7283 					    saddr, &nk->addr[pd2.didx],
7284 					    nk->port[pd2.didx], &uh.uh_sum,
7285 					    pd2.ip_sum, icmpsum,
7286 					    pd->ip_sum, 1, pd2.af);
7287 
7288 				switch (pd2.af) {
7289 #ifdef INET
7290 				case AF_INET:
7291 					m_copyback(pd->m, pd->off, ICMP_MINLEN,
7292 					    (caddr_t )&pd->hdr.icmp);
7293 					m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
7294 					break;
7295 #endif /* INET */
7296 #ifdef INET6
7297 				case AF_INET6:
7298 					m_copyback(pd->m, pd->off,
7299 					    sizeof(struct icmp6_hdr),
7300 					    (caddr_t )&pd->hdr.icmp6);
7301 					m_copyback(pd->m, ipoff2, sizeof(h2_6),
7302 					    (caddr_t )&h2_6);
7303 					break;
7304 #endif /* INET6 */
7305 				}
7306 				m_copyback(pd->m, pd2.off, sizeof(uh), (caddr_t)&uh);
7307 			}
7308 			return (PF_PASS);
7309 			break;
7310 		}
7311 #ifdef INET
7312 		case IPPROTO_ICMP: {
7313 			struct icmp	*iih = &pd2.hdr.icmp;
7314 
7315 			if (pd2.af != AF_INET) {
7316 				REASON_SET(reason, PFRES_NORM);
7317 				return (PF_DROP);
7318 			}
7319 
7320 			if (!pf_pull_hdr(pd->m, pd2.off, iih, ICMP_MINLEN,
7321 			    NULL, reason, pd2.af)) {
7322 				DPFPRINTF(PF_DEBUG_MISC,
7323 				    ("pf: ICMP error message too short i"
7324 				    "(icmp)\n"));
7325 				return (PF_DROP);
7326 			}
7327 
7328 			icmpid = iih->icmp_id;
7329 			pf_icmp_mapping(&pd2, iih->icmp_type,
7330 			    &icmp_dir, &multi, &virtual_id, &virtual_type);
7331 
7332 			ret = pf_icmp_state_lookup(&key, &pd2, state,
7333 			    pd2.dir, virtual_id, virtual_type,
7334 			    icmp_dir, &iidx, PF_ICMP_MULTI_NONE, 1);
7335 			if (ret >= 0) {
7336 				MPASS(*state == NULL);
7337 				return (ret);
7338 			}
7339 
7340 			/* translate source/destination address, if necessary */
7341 			if ((*state)->key[PF_SK_WIRE] !=
7342 			    (*state)->key[PF_SK_STACK]) {
7343 				struct pf_state_key *nk =
7344 				    (*state)->key[pd->didx];
7345 
7346 				if (PF_ANEQ(pd2.src,
7347 				    &nk->addr[pd2.sidx], pd2.af) ||
7348 				    (virtual_type == htons(ICMP_ECHO) &&
7349 				    nk->port[iidx] != iih->icmp_id))
7350 					pf_change_icmp(pd2.src,
7351 					    (virtual_type == htons(ICMP_ECHO)) ?
7352 					    &iih->icmp_id : NULL,
7353 					    daddr, &nk->addr[pd2.sidx],
7354 					    (virtual_type == htons(ICMP_ECHO)) ?
7355 					    nk->port[iidx] : 0, NULL,
7356 					    pd2.ip_sum, icmpsum,
7357 					    pd->ip_sum, 0, AF_INET);
7358 
7359 				if (PF_ANEQ(pd2.dst,
7360 				    &nk->addr[pd2.didx], pd2.af))
7361 					pf_change_icmp(pd2.dst, NULL, NULL,
7362 					    &nk->addr[pd2.didx], 0, NULL,
7363 					    pd2.ip_sum, icmpsum, pd->ip_sum, 0,
7364 					    AF_INET);
7365 
7366 				m_copyback(pd->m, pd->off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
7367 				m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
7368 				m_copyback(pd->m, pd2.off, ICMP_MINLEN, (caddr_t)iih);
7369 			}
7370 			return (PF_PASS);
7371 			break;
7372 		}
7373 #endif /* INET */
7374 #ifdef INET6
7375 		case IPPROTO_ICMPV6: {
7376 			struct icmp6_hdr	*iih = &pd2.hdr.icmp6;
7377 
7378 			if (pd2.af != AF_INET6) {
7379 				REASON_SET(reason, PFRES_NORM);
7380 				return (PF_DROP);
7381 			}
7382 
7383 			if (!pf_pull_hdr(pd->m, pd2.off, iih,
7384 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
7385 				DPFPRINTF(PF_DEBUG_MISC,
7386 				    ("pf: ICMP error message too short "
7387 				    "(icmp6)\n"));
7388 				return (PF_DROP);
7389 			}
7390 
7391 			pf_icmp_mapping(&pd2, iih->icmp6_type,
7392 			    &icmp_dir, &multi, &virtual_id, &virtual_type);
7393 
7394 			ret = pf_icmp_state_lookup(&key, &pd2, state,
7395 			    pd->dir, virtual_id, virtual_type,
7396 			    icmp_dir, &iidx, PF_ICMP_MULTI_NONE, 1);
7397 			if (ret >= 0) {
7398 				MPASS(*state == NULL);
7399 				if (ret == PF_DROP && pd2.af == AF_INET6 &&
7400 				    icmp_dir == PF_OUT) {
7401 					ret = pf_icmp_state_lookup(&key, &pd2,
7402 					    state, pd->dir,
7403 					    virtual_id, virtual_type,
7404 					    icmp_dir, &iidx, multi, 1);
7405 					if (ret >= 0) {
7406 						MPASS(*state == NULL);
7407 						return (ret);
7408 					}
7409 				} else
7410 					return (ret);
7411 			}
7412 
7413 			/* translate source/destination address, if necessary */
7414 			if ((*state)->key[PF_SK_WIRE] !=
7415 			    (*state)->key[PF_SK_STACK]) {
7416 				struct pf_state_key *nk =
7417 				    (*state)->key[pd->didx];
7418 
7419 				if (PF_ANEQ(pd2.src,
7420 				    &nk->addr[pd2.sidx], pd2.af) ||
7421 				    ((virtual_type == htons(ICMP6_ECHO_REQUEST)) &&
7422 				    nk->port[pd2.sidx] != iih->icmp6_id))
7423 					pf_change_icmp(pd2.src,
7424 					    (virtual_type == htons(ICMP6_ECHO_REQUEST))
7425 					    ? &iih->icmp6_id : NULL,
7426 					    daddr, &nk->addr[pd2.sidx],
7427 					    (virtual_type == htons(ICMP6_ECHO_REQUEST))
7428 					    ? nk->port[iidx] : 0, NULL,
7429 					    pd2.ip_sum, icmpsum,
7430 					    pd->ip_sum, 0, AF_INET6);
7431 
7432 				if (PF_ANEQ(pd2.dst,
7433 				    &nk->addr[pd2.didx], pd2.af))
7434 					pf_change_icmp(pd2.dst, NULL, NULL,
7435 					    &nk->addr[pd2.didx], 0, NULL,
7436 					    pd2.ip_sum, icmpsum,
7437 					    pd->ip_sum, 0, AF_INET6);
7438 
7439 				m_copyback(pd->m, pd->off, sizeof(struct icmp6_hdr),
7440 				    (caddr_t)&pd->hdr.icmp6);
7441 				m_copyback(pd->m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
7442 				m_copyback(pd->m, pd2.off, sizeof(struct icmp6_hdr),
7443 				    (caddr_t)iih);
7444 			}
7445 			return (PF_PASS);
7446 			break;
7447 		}
7448 #endif /* INET6 */
7449 		default: {
7450 			key.af = pd2.af;
7451 			key.proto = pd2.proto;
7452 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
7453 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
7454 			key.port[0] = key.port[1] = 0;
7455 
7456 			STATE_LOOKUP(&key, *state, pd);
7457 
7458 			/* translate source/destination address, if necessary */
7459 			if ((*state)->key[PF_SK_WIRE] !=
7460 			    (*state)->key[PF_SK_STACK]) {
7461 				struct pf_state_key *nk =
7462 				    (*state)->key[pd->didx];
7463 
7464 				if (PF_ANEQ(pd2.src,
7465 				    &nk->addr[pd2.sidx], pd2.af))
7466 					pf_change_icmp(pd2.src, NULL, daddr,
7467 					    &nk->addr[pd2.sidx], 0, NULL,
7468 					    pd2.ip_sum, icmpsum,
7469 					    pd->ip_sum, 0, pd2.af);
7470 
7471 				if (PF_ANEQ(pd2.dst,
7472 				    &nk->addr[pd2.didx], pd2.af))
7473 					pf_change_icmp(pd2.dst, NULL, saddr,
7474 					    &nk->addr[pd2.didx], 0, NULL,
7475 					    pd2.ip_sum, icmpsum,
7476 					    pd->ip_sum, 0, pd2.af);
7477 
7478 				switch (pd2.af) {
7479 #ifdef INET
7480 				case AF_INET:
7481 					m_copyback(pd->m, pd->off, ICMP_MINLEN,
7482 					    (caddr_t)&pd->hdr.icmp);
7483 					m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
7484 					break;
7485 #endif /* INET */
7486 #ifdef INET6
7487 				case AF_INET6:
7488 					m_copyback(pd->m, pd->off,
7489 					    sizeof(struct icmp6_hdr),
7490 					    (caddr_t )&pd->hdr.icmp6);
7491 					m_copyback(pd->m, ipoff2, sizeof(h2_6),
7492 					    (caddr_t )&h2_6);
7493 					break;
7494 #endif /* INET6 */
7495 				}
7496 			}
7497 			return (PF_PASS);
7498 			break;
7499 		}
7500 		}
7501 	}
7502 }
7503 
7504 static int
pf_test_state_other(struct pf_kstate ** state,struct pf_pdesc * pd)7505 pf_test_state_other(struct pf_kstate **state, struct pf_pdesc *pd)
7506 {
7507 	struct pf_state_peer	*src, *dst;
7508 	struct pf_state_key_cmp	 key;
7509 	uint8_t			 psrc, pdst;
7510 
7511 	bzero(&key, sizeof(key));
7512 	key.af = pd->af;
7513 	key.proto = pd->proto;
7514 	if (pd->dir == PF_IN)	{
7515 		PF_ACPY(&key.addr[0], pd->src, key.af);
7516 		PF_ACPY(&key.addr[1], pd->dst, key.af);
7517 		key.port[0] = key.port[1] = 0;
7518 	} else {
7519 		PF_ACPY(&key.addr[1], pd->src, key.af);
7520 		PF_ACPY(&key.addr[0], pd->dst, key.af);
7521 		key.port[1] = key.port[0] = 0;
7522 	}
7523 
7524 	STATE_LOOKUP(&key, *state, pd);
7525 
7526 	if (pd->dir == (*state)->direction) {
7527 		src = &(*state)->src;
7528 		dst = &(*state)->dst;
7529 		psrc = PF_PEER_SRC;
7530 		pdst = PF_PEER_DST;
7531 	} else {
7532 		src = &(*state)->dst;
7533 		dst = &(*state)->src;
7534 		psrc = PF_PEER_DST;
7535 		pdst = PF_PEER_SRC;
7536 	}
7537 
7538 	/* update states */
7539 	if (src->state < PFOTHERS_SINGLE)
7540 		pf_set_protostate(*state, psrc, PFOTHERS_SINGLE);
7541 	if (dst->state == PFOTHERS_SINGLE)
7542 		pf_set_protostate(*state, pdst, PFOTHERS_MULTIPLE);
7543 
7544 	/* update expire time */
7545 	(*state)->expire = pf_get_uptime();
7546 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
7547 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
7548 	else
7549 		(*state)->timeout = PFTM_OTHER_SINGLE;
7550 
7551 	/* translate source/destination address, if necessary */
7552 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
7553 		struct pf_state_key *nk = (*state)->key[pd->didx];
7554 
7555 		KASSERT(nk, ("%s: nk is null", __func__));
7556 		KASSERT(pd, ("%s: pd is null", __func__));
7557 		KASSERT(pd->src, ("%s: pd->src is null", __func__));
7558 		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
7559 		switch (pd->af) {
7560 #ifdef INET
7561 		case AF_INET:
7562 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
7563 				pf_change_a(&pd->src->v4.s_addr,
7564 				    pd->ip_sum,
7565 				    nk->addr[pd->sidx].v4.s_addr,
7566 				    0);
7567 
7568 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
7569 				pf_change_a(&pd->dst->v4.s_addr,
7570 				    pd->ip_sum,
7571 				    nk->addr[pd->didx].v4.s_addr,
7572 				    0);
7573 
7574 			break;
7575 #endif /* INET */
7576 #ifdef INET6
7577 		case AF_INET6:
7578 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET6))
7579 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
7580 
7581 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET6))
7582 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
7583 #endif /* INET6 */
7584 		}
7585 	}
7586 	return (PF_PASS);
7587 }
7588 
7589 /*
7590  * ipoff and off are measured from the start of the mbuf chain.
7591  * h must be at "ipoff" on the mbuf chain.
7592  */
7593 void *
pf_pull_hdr(const struct mbuf * m,int off,void * p,int len,u_short * actionp,u_short * reasonp,sa_family_t af)7594 pf_pull_hdr(const struct mbuf *m, int off, void *p, int len,
7595     u_short *actionp, u_short *reasonp, sa_family_t af)
7596 {
7597 	switch (af) {
7598 #ifdef INET
7599 	case AF_INET: {
7600 		const struct ip	*h = mtod(m, struct ip *);
7601 		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
7602 
7603 		if (fragoff) {
7604 			if (fragoff >= len)
7605 				ACTION_SET(actionp, PF_PASS);
7606 			else {
7607 				ACTION_SET(actionp, PF_DROP);
7608 				REASON_SET(reasonp, PFRES_FRAG);
7609 			}
7610 			return (NULL);
7611 		}
7612 		if (m->m_pkthdr.len < off + len ||
7613 		    ntohs(h->ip_len) < off + len) {
7614 			ACTION_SET(actionp, PF_DROP);
7615 			REASON_SET(reasonp, PFRES_SHORT);
7616 			return (NULL);
7617 		}
7618 		break;
7619 	}
7620 #endif /* INET */
7621 #ifdef INET6
7622 	case AF_INET6: {
7623 		const struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
7624 
7625 		if (m->m_pkthdr.len < off + len ||
7626 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
7627 		    (unsigned)(off + len)) {
7628 			ACTION_SET(actionp, PF_DROP);
7629 			REASON_SET(reasonp, PFRES_SHORT);
7630 			return (NULL);
7631 		}
7632 		break;
7633 	}
7634 #endif /* INET6 */
7635 	}
7636 	m_copydata(m, off, len, p);
7637 	return (p);
7638 }
7639 
7640 int
pf_routable(struct pf_addr * addr,sa_family_t af,struct pfi_kkif * kif,int rtableid)7641 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kkif *kif,
7642     int rtableid)
7643 {
7644 	struct ifnet		*ifp;
7645 
7646 	/*
7647 	 * Skip check for addresses with embedded interface scope,
7648 	 * as they would always match anyway.
7649 	 */
7650 	if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
7651 		return (1);
7652 
7653 	if (af != AF_INET && af != AF_INET6)
7654 		return (0);
7655 
7656 	if (kif == V_pfi_all)
7657 		return (1);
7658 
7659 	/* Skip checks for ipsec interfaces */
7660 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
7661 		return (1);
7662 
7663 	ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
7664 
7665 	switch (af) {
7666 #ifdef INET6
7667 	case AF_INET6:
7668 		return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
7669 		    ifp));
7670 #endif
7671 #ifdef INET
7672 	case AF_INET:
7673 		return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
7674 		    ifp));
7675 #endif
7676 	}
7677 
7678 	return (0);
7679 }
7680 
7681 #ifdef INET
7682 static void
pf_route(struct mbuf ** m,struct pf_krule * r,struct ifnet * oifp,struct pf_kstate * s,struct pf_pdesc * pd,struct inpcb * inp)7683 pf_route(struct mbuf **m, struct pf_krule *r, struct ifnet *oifp,
7684     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
7685 {
7686 	struct mbuf		*m0, *m1, *md;
7687 	struct sockaddr_in	dst;
7688 	struct ip		*ip;
7689 	struct pfi_kkif		*nkif = NULL;
7690 	struct ifnet		*ifp = NULL;
7691 	struct pf_addr		 naddr;
7692 	int			 error = 0;
7693 	uint16_t		 ip_len, ip_off;
7694 	uint16_t		 tmp;
7695 	int			 r_rt, r_dir;
7696 
7697 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
7698 
7699 	SDT_PROBE4(pf, ip, route_to, entry, *m, pd, s, oifp);
7700 
7701 	if (s) {
7702 		r_rt = s->rt;
7703 		r_dir = s->direction;
7704 	} else {
7705 		r_rt = r->rt;
7706 		r_dir = r->direction;
7707 	}
7708 
7709 	KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
7710 	    r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
7711 	    __func__));
7712 
7713 	if ((pd->pf_mtag == NULL &&
7714 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
7715 	    pd->pf_mtag->routed++ > 3) {
7716 		m0 = *m;
7717 		*m = NULL;
7718 		SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7719 		goto bad_locked;
7720 	}
7721 
7722 	if (r_rt == PF_DUPTO) {
7723 		if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
7724 			if (s == NULL) {
7725 				ifp = r->rpool.cur->kif ?
7726 				    r->rpool.cur->kif->pfik_ifp : NULL;
7727 			} else {
7728 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7729 				/* If pfsync'd */
7730 				if (ifp == NULL && r->rpool.cur != NULL)
7731 					ifp = r->rpool.cur->kif ?
7732 					    r->rpool.cur->kif->pfik_ifp : NULL;
7733 				PF_STATE_UNLOCK(s);
7734 			}
7735 			if (ifp == oifp) {
7736 				/* When the 2nd interface is not skipped */
7737 				return;
7738 			} else {
7739 				m0 = *m;
7740 				*m = NULL;
7741 				SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7742 				goto bad;
7743 			}
7744 		} else {
7745 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
7746 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
7747 				if (s)
7748 					PF_STATE_UNLOCK(s);
7749 				return;
7750 			}
7751 		}
7752 	} else {
7753 		if ((r_rt == PF_REPLYTO) == (r_dir == pd->dir)) {
7754 			pf_dummynet(pd, s, r, m);
7755 			if (s)
7756 				PF_STATE_UNLOCK(s);
7757 			return;
7758 		}
7759 		m0 = *m;
7760 	}
7761 
7762 	ip = mtod(m0, struct ip *);
7763 
7764 	bzero(&dst, sizeof(dst));
7765 	dst.sin_family = AF_INET;
7766 	dst.sin_len = sizeof(dst);
7767 	dst.sin_addr = ip->ip_dst;
7768 
7769 	bzero(&naddr, sizeof(naddr));
7770 
7771 	if (s == NULL) {
7772 		if (TAILQ_EMPTY(&r->rpool.list)) {
7773 			DPFPRINTF(PF_DEBUG_URGENT,
7774 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
7775 			SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7776 			goto bad_locked;
7777 		}
7778 		pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
7779 		    &naddr, &nkif, NULL);
7780 		if (!PF_AZERO(&naddr, AF_INET))
7781 			dst.sin_addr.s_addr = naddr.v4.s_addr;
7782 		ifp = nkif ? nkif->pfik_ifp : NULL;
7783 	} else {
7784 		struct pfi_kkif *kif;
7785 
7786 		if (!PF_AZERO(&s->rt_addr, AF_INET))
7787 			dst.sin_addr.s_addr =
7788 			    s->rt_addr.v4.s_addr;
7789 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7790 		kif = s->rt_kif;
7791 		/* If pfsync'd */
7792 		if (ifp == NULL && r->rpool.cur != NULL) {
7793 			ifp = r->rpool.cur->kif ?
7794 			    r->rpool.cur->kif->pfik_ifp : NULL;
7795 			kif = r->rpool.cur->kif;
7796 		}
7797 		if (ifp != NULL && kif != NULL &&
7798 		    r->rule_flag & PFRULE_IFBOUND &&
7799 		    r->rt == PF_REPLYTO &&
7800 		    s->kif == V_pfi_all) {
7801 			s->kif = kif;
7802 			s->orig_kif = oifp->if_pf_kif;
7803 		}
7804 
7805 		PF_STATE_UNLOCK(s);
7806 	}
7807 
7808 	if (ifp == NULL) {
7809 		SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7810 		goto bad;
7811 	}
7812 
7813 	if (pd->dir == PF_IN) {
7814 		if (pf_test(AF_INET, PF_OUT, PFIL_FWD, ifp, &m0, inp,
7815 		    &pd->act) != PF_PASS) {
7816 			SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7817 			goto bad;
7818 		} else if (m0 == NULL) {
7819 			SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7820 			goto done;
7821 		}
7822 		if (m0->m_len < sizeof(struct ip)) {
7823 			DPFPRINTF(PF_DEBUG_URGENT,
7824 			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
7825 			SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7826 			goto bad;
7827 		}
7828 		ip = mtod(m0, struct ip *);
7829 	}
7830 
7831 	if (ifp->if_flags & IFF_LOOPBACK)
7832 		m0->m_flags |= M_SKIP_FIREWALL;
7833 
7834 	ip_len = ntohs(ip->ip_len);
7835 	ip_off = ntohs(ip->ip_off);
7836 
7837 	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
7838 	m0->m_pkthdr.csum_flags |= CSUM_IP;
7839 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
7840 		in_delayed_cksum(m0);
7841 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
7842 	}
7843 	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
7844 		pf_sctp_checksum(m0, (uint32_t)(ip->ip_hl << 2));
7845 		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
7846 	}
7847 
7848 	if (pd->dir == PF_IN) {
7849 		/*
7850 		 * Make sure dummynet gets the correct direction, in case it needs to
7851 		 * re-inject later.
7852 		 */
7853 		pd->dir = PF_OUT;
7854 
7855 		/*
7856 		 * The following processing is actually the rest of the inbound processing, even
7857 		 * though we've marked it as outbound (so we don't look through dummynet) and it
7858 		 * happens after the outbound processing (pf_test(PF_OUT) above).
7859 		 * Swap the dummynet pipe numbers, because it's going to come to the wrong
7860 		 * conclusion about what direction it's processing, and we can't fix it or it
7861 		 * will re-inject incorrectly. Swapping the pipe numbers means that its incorrect
7862 		 * decision will pick the right pipe, and everything will mostly work as expected.
7863 		 */
7864 		tmp = pd->act.dnrpipe;
7865 		pd->act.dnrpipe = pd->act.dnpipe;
7866 		pd->act.dnpipe = tmp;
7867 	}
7868 
7869 	/*
7870 	 * If small enough for interface, or the interface will take
7871 	 * care of the fragmentation for us, we can just send directly.
7872 	 */
7873 	if (ip_len <= ifp->if_mtu ||
7874 	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
7875 		ip->ip_sum = 0;
7876 		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
7877 			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
7878 			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
7879 		}
7880 		m_clrprotoflags(m0);	/* Avoid confusing lower layers. */
7881 
7882 		md = m0;
7883 		error = pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
7884 		if (md != NULL) {
7885 			error = (*ifp->if_output)(ifp, md, sintosa(&dst), NULL);
7886 			SDT_PROBE2(pf, ip, route_to, output, ifp, error);
7887 		}
7888 		goto done;
7889 	}
7890 
7891 	/* Balk when DF bit is set or the interface didn't support TSO. */
7892 	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
7893 		error = EMSGSIZE;
7894 		KMOD_IPSTAT_INC(ips_cantfrag);
7895 		if (r_rt != PF_DUPTO) {
7896 			if (s && s->nat_rule != NULL)
7897 				PACKET_UNDO_NAT(m0, pd,
7898 				    (ip->ip_hl << 2) + (ip_off & IP_OFFMASK),
7899 				    s);
7900 
7901 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
7902 			    ifp->if_mtu);
7903 			SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7904 			goto done;
7905 		} else {
7906 			SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7907 			goto bad;
7908 		}
7909 	}
7910 
7911 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
7912 	if (error) {
7913 		SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
7914 		goto bad;
7915 	}
7916 
7917 	for (; m0; m0 = m1) {
7918 		m1 = m0->m_nextpkt;
7919 		m0->m_nextpkt = NULL;
7920 		if (error == 0) {
7921 			m_clrprotoflags(m0);
7922 			md = m0;
7923 			pd->pf_mtag = pf_find_mtag(md);
7924 			error = pf_dummynet_route(pd, s, r, ifp,
7925 			    sintosa(&dst), &md);
7926 			if (md != NULL) {
7927 				error = (*ifp->if_output)(ifp, md,
7928 				    sintosa(&dst), NULL);
7929 				SDT_PROBE2(pf, ip, route_to, output, ifp, error);
7930 			}
7931 		} else
7932 			m_freem(m0);
7933 	}
7934 
7935 	if (error == 0)
7936 		KMOD_IPSTAT_INC(ips_fragmented);
7937 
7938 done:
7939 	if (r_rt != PF_DUPTO)
7940 		*m = NULL;
7941 	return;
7942 
7943 bad_locked:
7944 	if (s)
7945 		PF_STATE_UNLOCK(s);
7946 bad:
7947 	m_freem(m0);
7948 	goto done;
7949 }
7950 #endif /* INET */
7951 
7952 #ifdef INET6
7953 static void
pf_route6(struct mbuf ** m,struct pf_krule * r,struct ifnet * oifp,struct pf_kstate * s,struct pf_pdesc * pd,struct inpcb * inp)7954 pf_route6(struct mbuf **m, struct pf_krule *r, struct ifnet *oifp,
7955     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
7956 {
7957 	struct mbuf		*m0, *md;
7958 	struct m_tag		*mtag;
7959 	struct sockaddr_in6	dst;
7960 	struct ip6_hdr		*ip6;
7961 	struct pfi_kkif		*nkif = NULL;
7962 	struct ifnet		*ifp = NULL;
7963 	struct pf_addr		 naddr;
7964 	int			 r_rt, r_dir;
7965 
7966 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
7967 
7968 	SDT_PROBE4(pf, ip6, route_to, entry, *m, pd, s, oifp);
7969 
7970 	if (s) {
7971 		r_rt = s->rt;
7972 		r_dir = s->direction;
7973 	} else {
7974 		r_rt = r->rt;
7975 		r_dir = r->direction;
7976 	}
7977 
7978 	KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
7979 	    r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
7980 	    __func__));
7981 
7982 	if ((pd->pf_mtag == NULL &&
7983 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
7984 	    pd->pf_mtag->routed++ > 3) {
7985 		m0 = *m;
7986 		*m = NULL;
7987 		SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
7988 		goto bad_locked;
7989 	}
7990 
7991 	if (r_rt == PF_DUPTO) {
7992 		if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
7993 			if (s == NULL) {
7994 				ifp = r->rpool.cur->kif ?
7995 				    r->rpool.cur->kif->pfik_ifp : NULL;
7996 			} else {
7997 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7998 				/* If pfsync'd */
7999 				if (ifp == NULL && r->rpool.cur != NULL)
8000 					ifp = r->rpool.cur->kif ?
8001 					    r->rpool.cur->kif->pfik_ifp : NULL;
8002 				PF_STATE_UNLOCK(s);
8003 			}
8004 			if (ifp == oifp) {
8005 				/* When the 2nd interface is not skipped */
8006 				return;
8007 			} else {
8008 				m0 = *m;
8009 				*m = NULL;
8010 				SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
8011 				goto bad;
8012 			}
8013 		} else {
8014 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
8015 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
8016 				if (s)
8017 					PF_STATE_UNLOCK(s);
8018 				return;
8019 			}
8020 		}
8021 	} else {
8022 		if ((r_rt == PF_REPLYTO) == (r_dir == pd->dir)) {
8023 			pf_dummynet(pd, s, r, m);
8024 			if (s)
8025 				PF_STATE_UNLOCK(s);
8026 			return;
8027 		}
8028 		m0 = *m;
8029 	}
8030 
8031 	ip6 = mtod(m0, struct ip6_hdr *);
8032 
8033 	bzero(&dst, sizeof(dst));
8034 	dst.sin6_family = AF_INET6;
8035 	dst.sin6_len = sizeof(dst);
8036 	dst.sin6_addr = ip6->ip6_dst;
8037 
8038 	bzero(&naddr, sizeof(naddr));
8039 
8040 	if (s == NULL) {
8041 		if (TAILQ_EMPTY(&r->rpool.list)) {
8042 			DPFPRINTF(PF_DEBUG_URGENT,
8043 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
8044 			SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
8045 			goto bad_locked;
8046 		}
8047 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
8048 		    &naddr, &nkif, NULL);
8049 		if (!PF_AZERO(&naddr, AF_INET6))
8050 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
8051 			    &naddr, AF_INET6);
8052 		ifp = nkif ? nkif->pfik_ifp : NULL;
8053 	} else {
8054 		struct pfi_kkif *kif;
8055 
8056 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
8057 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
8058 			    &s->rt_addr, AF_INET6);
8059 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
8060 		kif = s->rt_kif;
8061 		/* If pfsync'd */
8062 		if (ifp == NULL && r->rpool.cur != NULL) {
8063 			ifp = r->rpool.cur->kif ?
8064 			    r->rpool.cur->kif->pfik_ifp : NULL;
8065 			kif = r->rpool.cur->kif;
8066 		}
8067 		if (ifp != NULL && kif != NULL &&
8068 		    r->rule_flag & PFRULE_IFBOUND &&
8069 		    r->rt == PF_REPLYTO &&
8070 		    s->kif == V_pfi_all) {
8071 			s->kif = kif;
8072 			s->orig_kif = oifp->if_pf_kif;
8073 		}
8074 	}
8075 
8076 	if (s)
8077 		PF_STATE_UNLOCK(s);
8078 
8079 	if (ifp == NULL) {
8080 		SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
8081 		goto bad;
8082 	}
8083 
8084 	if (pd->dir == PF_IN) {
8085 		if (pf_test(AF_INET6, PF_OUT, PFIL_FWD | PF_PFIL_NOREFRAGMENT,
8086 		    ifp, &m0, inp, &pd->act) != PF_PASS) {
8087 			SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
8088 			goto bad;
8089 		} else if (m0 == NULL) {
8090 			SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
8091 			goto done;
8092 		}
8093 		if (m0->m_len < sizeof(struct ip6_hdr)) {
8094 			DPFPRINTF(PF_DEBUG_URGENT,
8095 			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
8096 			    __func__));
8097 			SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
8098 			goto bad;
8099 		}
8100 		ip6 = mtod(m0, struct ip6_hdr *);
8101 	}
8102 
8103 	if (ifp->if_flags & IFF_LOOPBACK)
8104 		m0->m_flags |= M_SKIP_FIREWALL;
8105 
8106 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
8107 	    ~ifp->if_hwassist) {
8108 		uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
8109 		in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
8110 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
8111 	}
8112 
8113 	/*
8114 	 * If the packet is too large for the outgoing interface,
8115 	 * send back an icmp6 error.
8116 	 */
8117 	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
8118 		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
8119 	mtag = m_tag_find(m0, PACKET_TAG_PF_REASSEMBLED, NULL);
8120 	if (mtag != NULL) {
8121 		int ret __sdt_used;
8122 		ret = pf_refragment6(ifp, &m0, mtag, ifp, true);
8123 		SDT_PROBE2(pf, ip6, route_to, output, ifp, ret);
8124 		goto done;
8125 	}
8126 
8127 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
8128 		md = m0;
8129 		pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
8130 		if (md != NULL) {
8131 			int ret __sdt_used;
8132 			ret = nd6_output_ifp(ifp, ifp, md, &dst, NULL);
8133 			SDT_PROBE2(pf, ip6, route_to, output, ifp, ret);
8134 		}
8135 	}
8136 	else {
8137 		in6_ifstat_inc(ifp, ifs6_in_toobig);
8138 		if (r_rt != PF_DUPTO) {
8139 			if (s && s->nat_rule != NULL)
8140 				PACKET_UNDO_NAT(m0, pd,
8141 				    ((caddr_t)ip6 - m0->m_data) +
8142 				    sizeof(struct ip6_hdr), s);
8143 
8144 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
8145 			SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
8146 		} else {
8147 			SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
8148 			goto bad;
8149 		}
8150 	}
8151 
8152 done:
8153 	if (r_rt != PF_DUPTO)
8154 		*m = NULL;
8155 	return;
8156 
8157 bad_locked:
8158 	if (s)
8159 		PF_STATE_UNLOCK(s);
8160 bad:
8161 	m_freem(m0);
8162 	goto done;
8163 }
8164 #endif /* INET6 */
8165 
8166 /*
8167  * FreeBSD supports cksum offloads for the following drivers.
8168  *  em(4), fxp(4), lge(4), nge(4), re(4), ti(4), txp(4), xl(4)
8169  *
8170  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
8171  *  network driver performed cksum including pseudo header, need to verify
8172  *   csum_data
8173  * CSUM_DATA_VALID :
8174  *  network driver performed cksum, needs to additional pseudo header
8175  *  cksum computation with partial csum_data(i.e. lack of H/W support for
8176  *  pseudo header, for instance sk(4) and possibly gem(4))
8177  *
8178  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
8179  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
8180  * TCP/UDP layer.
8181  * Also, set csum_data to 0xffff to force cksum validation.
8182  */
8183 static int
pf_check_proto_cksum(struct mbuf * m,int off,int len,u_int8_t p,sa_family_t af)8184 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
8185 {
8186 	u_int16_t sum = 0;
8187 	int hw_assist = 0;
8188 	struct ip *ip;
8189 
8190 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
8191 		return (1);
8192 	if (m->m_pkthdr.len < off + len)
8193 		return (1);
8194 
8195 	switch (p) {
8196 	case IPPROTO_TCP:
8197 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
8198 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
8199 				sum = m->m_pkthdr.csum_data;
8200 			} else {
8201 				ip = mtod(m, struct ip *);
8202 				sum = in_pseudo(ip->ip_src.s_addr,
8203 				ip->ip_dst.s_addr, htonl((u_short)len +
8204 				m->m_pkthdr.csum_data + IPPROTO_TCP));
8205 			}
8206 			sum ^= 0xffff;
8207 			++hw_assist;
8208 		}
8209 		break;
8210 	case IPPROTO_UDP:
8211 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
8212 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
8213 				sum = m->m_pkthdr.csum_data;
8214 			} else {
8215 				ip = mtod(m, struct ip *);
8216 				sum = in_pseudo(ip->ip_src.s_addr,
8217 				ip->ip_dst.s_addr, htonl((u_short)len +
8218 				m->m_pkthdr.csum_data + IPPROTO_UDP));
8219 			}
8220 			sum ^= 0xffff;
8221 			++hw_assist;
8222 		}
8223 		break;
8224 	case IPPROTO_ICMP:
8225 #ifdef INET6
8226 	case IPPROTO_ICMPV6:
8227 #endif /* INET6 */
8228 		break;
8229 	default:
8230 		return (1);
8231 	}
8232 
8233 	if (!hw_assist) {
8234 		switch (af) {
8235 		case AF_INET:
8236 			if (p == IPPROTO_ICMP) {
8237 				if (m->m_len < off)
8238 					return (1);
8239 				m->m_data += off;
8240 				m->m_len -= off;
8241 				sum = in_cksum(m, len);
8242 				m->m_data -= off;
8243 				m->m_len += off;
8244 			} else {
8245 				if (m->m_len < sizeof(struct ip))
8246 					return (1);
8247 				sum = in4_cksum(m, p, off, len);
8248 			}
8249 			break;
8250 #ifdef INET6
8251 		case AF_INET6:
8252 			if (m->m_len < sizeof(struct ip6_hdr))
8253 				return (1);
8254 			sum = in6_cksum(m, p, off, len);
8255 			break;
8256 #endif /* INET6 */
8257 		}
8258 	}
8259 	if (sum) {
8260 		switch (p) {
8261 		case IPPROTO_TCP:
8262 		    {
8263 			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
8264 			break;
8265 		    }
8266 		case IPPROTO_UDP:
8267 		    {
8268 			KMOD_UDPSTAT_INC(udps_badsum);
8269 			break;
8270 		    }
8271 #ifdef INET
8272 		case IPPROTO_ICMP:
8273 		    {
8274 			KMOD_ICMPSTAT_INC(icps_checksum);
8275 			break;
8276 		    }
8277 #endif
8278 #ifdef INET6
8279 		case IPPROTO_ICMPV6:
8280 		    {
8281 			KMOD_ICMP6STAT_INC(icp6s_checksum);
8282 			break;
8283 		    }
8284 #endif /* INET6 */
8285 		}
8286 		return (1);
8287 	} else {
8288 		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
8289 			m->m_pkthdr.csum_flags |=
8290 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
8291 			m->m_pkthdr.csum_data = 0xffff;
8292 		}
8293 	}
8294 	return (0);
8295 }
8296 
8297 static bool
pf_pdesc_to_dnflow(const struct pf_pdesc * pd,const struct pf_krule * r,const struct pf_kstate * s,struct ip_fw_args * dnflow)8298 pf_pdesc_to_dnflow(const struct pf_pdesc *pd, const struct pf_krule *r,
8299     const struct pf_kstate *s, struct ip_fw_args *dnflow)
8300 {
8301 	int dndir = r->direction;
8302 
8303 	if (s && dndir == PF_INOUT) {
8304 		dndir = s->direction;
8305 	} else if (dndir == PF_INOUT) {
8306 		/* Assume primary direction. Happens when we've set dnpipe in
8307 		 * the ethernet level code. */
8308 		dndir = pd->dir;
8309 	}
8310 
8311 	if (pd->pf_mtag->flags & PF_MTAG_FLAG_DUMMYNETED)
8312 		return (false);
8313 
8314 	memset(dnflow, 0, sizeof(*dnflow));
8315 
8316 	if (pd->dport != NULL)
8317 		dnflow->f_id.dst_port = ntohs(*pd->dport);
8318 	if (pd->sport != NULL)
8319 		dnflow->f_id.src_port = ntohs(*pd->sport);
8320 
8321 	if (pd->dir == PF_IN)
8322 		dnflow->flags |= IPFW_ARGS_IN;
8323 	else
8324 		dnflow->flags |= IPFW_ARGS_OUT;
8325 
8326 	if (pd->dir != dndir && pd->act.dnrpipe) {
8327 		dnflow->rule.info = pd->act.dnrpipe;
8328 	}
8329 	else if (pd->dir == dndir && pd->act.dnpipe) {
8330 		dnflow->rule.info = pd->act.dnpipe;
8331 	}
8332 	else {
8333 		return (false);
8334 	}
8335 
8336 	dnflow->rule.info |= IPFW_IS_DUMMYNET;
8337 	if (r->free_flags & PFRULE_DN_IS_PIPE || pd->act.flags & PFSTATE_DN_IS_PIPE)
8338 		dnflow->rule.info |= IPFW_IS_PIPE;
8339 
8340 	dnflow->f_id.proto = pd->proto;
8341 	dnflow->f_id.extra = dnflow->rule.info;
8342 	switch (pd->af) {
8343 	case AF_INET:
8344 		dnflow->f_id.addr_type = 4;
8345 		dnflow->f_id.src_ip = ntohl(pd->src->v4.s_addr);
8346 		dnflow->f_id.dst_ip = ntohl(pd->dst->v4.s_addr);
8347 		break;
8348 	case AF_INET6:
8349 		dnflow->flags |= IPFW_ARGS_IP6;
8350 		dnflow->f_id.addr_type = 6;
8351 		dnflow->f_id.src_ip6 = pd->src->v6;
8352 		dnflow->f_id.dst_ip6 = pd->dst->v6;
8353 		break;
8354 	}
8355 
8356 	return (true);
8357 }
8358 
8359 int
pf_test_eth(int dir,int pflags,struct ifnet * ifp,struct mbuf ** m0,struct inpcb * inp)8360 pf_test_eth(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
8361     struct inpcb *inp)
8362 {
8363 	struct pfi_kkif		*kif;
8364 	struct mbuf		*m = *m0;
8365 
8366 	M_ASSERTPKTHDR(m);
8367 	MPASS(ifp->if_vnet == curvnet);
8368 	NET_EPOCH_ASSERT();
8369 
8370 	if (!V_pf_status.running)
8371 		return (PF_PASS);
8372 
8373 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
8374 
8375 	if (kif == NULL) {
8376 		DPFPRINTF(PF_DEBUG_URGENT,
8377 		    ("%s: kif == NULL, if_xname %s\n", __func__, ifp->if_xname));
8378 		return (PF_DROP);
8379 	}
8380 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
8381 		return (PF_PASS);
8382 
8383 	if (m->m_flags & M_SKIP_FIREWALL)
8384 		return (PF_PASS);
8385 
8386 	if (__predict_false(! M_WRITABLE(*m0))) {
8387 		m = *m0 = m_unshare(*m0, M_NOWAIT);
8388 		if (*m0 == NULL)
8389 			return (PF_DROP);
8390 	}
8391 
8392 	/* Stateless! */
8393 	return (pf_test_eth_rule(dir, kif, m0));
8394 }
8395 
8396 static __inline void
pf_dummynet_flag_remove(struct mbuf * m,struct pf_mtag * pf_mtag)8397 pf_dummynet_flag_remove(struct mbuf *m, struct pf_mtag *pf_mtag)
8398 {
8399 	struct m_tag *mtag;
8400 
8401 	pf_mtag->flags &= ~PF_MTAG_FLAG_DUMMYNET;
8402 
8403 	/* dummynet adds this tag, but pf does not need it,
8404 	 * and keeping it creates unexpected behavior,
8405 	 * e.g. in case of divert(4) usage right after dummynet. */
8406 	mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
8407 	if (mtag != NULL)
8408 		m_tag_delete(m, mtag);
8409 }
8410 
8411 static int
pf_dummynet(struct pf_pdesc * pd,struct pf_kstate * s,struct pf_krule * r,struct mbuf ** m0)8412 pf_dummynet(struct pf_pdesc *pd, struct pf_kstate *s,
8413     struct pf_krule *r, struct mbuf **m0)
8414 {
8415 	return (pf_dummynet_route(pd, s, r, NULL, NULL, m0));
8416 }
8417 
8418 static int
pf_dummynet_route(struct pf_pdesc * pd,struct pf_kstate * s,struct pf_krule * r,struct ifnet * ifp,struct sockaddr * sa,struct mbuf ** m0)8419 pf_dummynet_route(struct pf_pdesc *pd, struct pf_kstate *s,
8420     struct pf_krule *r, struct ifnet *ifp, struct sockaddr *sa,
8421     struct mbuf **m0)
8422 {
8423 	struct ip_fw_args dnflow;
8424 
8425 	NET_EPOCH_ASSERT();
8426 
8427 	if (pd->act.dnpipe == 0 && pd->act.dnrpipe == 0)
8428 		return (0);
8429 
8430 	if (ip_dn_io_ptr == NULL) {
8431 		m_freem(*m0);
8432 		*m0 = NULL;
8433 		return (ENOMEM);
8434 	}
8435 
8436 	if (pd->pf_mtag == NULL &&
8437 	    ((pd->pf_mtag = pf_get_mtag(*m0)) == NULL)) {
8438 		m_freem(*m0);
8439 		*m0 = NULL;
8440 		return (ENOMEM);
8441 	}
8442 
8443 	if (ifp != NULL) {
8444 		pd->pf_mtag->flags |= PF_MTAG_FLAG_ROUTE_TO;
8445 
8446 		pd->pf_mtag->if_index = ifp->if_index;
8447 		pd->pf_mtag->if_idxgen = ifp->if_idxgen;
8448 
8449 		MPASS(sa != NULL);
8450 
8451 		switch (pd->af) {
8452 		case AF_INET:
8453 			memcpy(&pd->pf_mtag->dst, sa,
8454 			    sizeof(struct sockaddr_in));
8455 			break;
8456 		case AF_INET6:
8457 			memcpy(&pd->pf_mtag->dst, sa,
8458 			    sizeof(struct sockaddr_in6));
8459 			break;
8460 		}
8461 	}
8462 
8463 	if (s != NULL && s->nat_rule != NULL &&
8464 	    s->nat_rule->action == PF_RDR &&
8465 	    (
8466 #ifdef INET
8467 	    (pd->af == AF_INET && IN_LOOPBACK(ntohl(pd->dst->v4.s_addr))) ||
8468 #endif
8469 	    (pd->af == AF_INET6 && IN6_IS_ADDR_LOOPBACK(&pd->dst->v6)))) {
8470 		/*
8471 		 * If we're redirecting to loopback mark this packet
8472 		 * as being local. Otherwise it might get dropped
8473 		 * if dummynet re-injects.
8474 		 */
8475 		(*m0)->m_pkthdr.rcvif = V_loif;
8476 	}
8477 
8478 	if (pf_pdesc_to_dnflow(pd, r, s, &dnflow)) {
8479 		pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
8480 		pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNETED;
8481 		ip_dn_io_ptr(m0, &dnflow);
8482 		if (*m0 != NULL) {
8483 			pd->pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
8484 			pf_dummynet_flag_remove(*m0, pd->pf_mtag);
8485 		}
8486 	}
8487 
8488 	return (0);
8489 }
8490 
8491 #ifdef INET6
8492 static int
pf_walk_option6(struct mbuf * m,int off,int end,uint32_t * jumbolen,u_short * reason)8493 pf_walk_option6(struct mbuf *m, int off, int end, uint32_t *jumbolen,
8494     u_short *reason)
8495 {
8496 	struct ip6_opt		 opt;
8497 	struct ip6_opt_jumbo	 jumbo;
8498 	struct ip6_hdr		*h = mtod(m, struct ip6_hdr *);
8499 
8500 	while (off < end) {
8501 		if (!pf_pull_hdr(m, off, &opt.ip6o_type, sizeof(opt.ip6o_type),
8502 			NULL, reason, AF_INET6)) {
8503 			DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short opt type"));
8504 			return (PF_DROP);
8505 		}
8506 		if (opt.ip6o_type == IP6OPT_PAD1) {
8507 			off++;
8508 			continue;
8509 		}
8510 		if (!pf_pull_hdr(m, off, &opt, sizeof(opt), NULL, reason,
8511 			AF_INET6)) {
8512 			DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short opt"));
8513 			return (PF_DROP);
8514 		}
8515 		if (off + sizeof(opt) + opt.ip6o_len > end) {
8516 			DPFPRINTF(PF_DEBUG_MISC, ("IPv6 long opt"));
8517 			REASON_SET(reason, PFRES_IPOPTIONS);
8518 			return (PF_DROP);
8519 		}
8520 		switch (opt.ip6o_type) {
8521 		case IP6OPT_JUMBO:
8522 			if (*jumbolen != 0) {
8523 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 multiple jumbo"));
8524 				REASON_SET(reason, PFRES_IPOPTIONS);
8525 				return (PF_DROP);
8526 			}
8527 			if (ntohs(h->ip6_plen) != 0) {
8528 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 bad jumbo plen"));
8529 				REASON_SET(reason, PFRES_IPOPTIONS);
8530 				return (PF_DROP);
8531 			}
8532 			if (!pf_pull_hdr(m, off, &jumbo, sizeof(jumbo), NULL,
8533 				reason, AF_INET6)) {
8534 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short jumbo"));
8535 				return (PF_DROP);
8536 			}
8537 			memcpy(jumbolen, jumbo.ip6oj_jumbo_len,
8538 			    sizeof(*jumbolen));
8539 			*jumbolen = ntohl(*jumbolen);
8540 			if (*jumbolen < IPV6_MAXPACKET) {
8541 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short jumbolen"));
8542 				REASON_SET(reason, PFRES_IPOPTIONS);
8543 				return (PF_DROP);
8544 			}
8545 			break;
8546 		default:
8547 			break;
8548 		}
8549 		off += sizeof(opt) + opt.ip6o_len;
8550 	}
8551 
8552 	return (PF_PASS);
8553 }
8554 
8555 int
pf_walk_header6(struct mbuf * m,struct ip6_hdr * h,int * off,int * extoff,int * fragoff,uint8_t * nxt,uint32_t * jumbolen,u_short * reason)8556 pf_walk_header6(struct mbuf *m, struct ip6_hdr *h, int *off, int *extoff,
8557     int *fragoff, uint8_t *nxt, uint32_t *jumbolen, u_short *reason)
8558 {
8559 	struct ip6_frag		 frag;
8560 	struct ip6_ext		 ext;
8561 	struct ip6_rthdr	 rthdr;
8562 	int			 rthdr_cnt = 0;
8563 
8564 	*off += sizeof(struct ip6_hdr);
8565 	*extoff = *fragoff = 0;
8566 	*nxt = h->ip6_nxt;
8567 	*jumbolen = 0;
8568 	for (;;) {
8569 		switch (*nxt) {
8570 		case IPPROTO_FRAGMENT:
8571 			if (*fragoff != 0) {
8572 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 multiple fragment"));
8573 				REASON_SET(reason, PFRES_FRAG);
8574 				return (PF_DROP);
8575 			}
8576 			/* jumbo payload packets cannot be fragmented */
8577 			if (*jumbolen != 0) {
8578 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 fragmented jumbo"));
8579 				REASON_SET(reason, PFRES_FRAG);
8580 				return (PF_DROP);
8581 			}
8582 			if (!pf_pull_hdr(m, *off, &frag, sizeof(frag), NULL,
8583 				reason, AF_INET6)) {
8584 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short fragment"));
8585 				return (PF_DROP);
8586 			}
8587 			*fragoff = *off;
8588 			/* stop walking over non initial fragments */
8589 			if ((frag.ip6f_offlg & IP6F_OFF_MASK) != 0)
8590 				return (PF_PASS);
8591 			*off += sizeof(frag);
8592 			*nxt = frag.ip6f_nxt;
8593 			break;
8594 		case IPPROTO_ROUTING:
8595 			if (rthdr_cnt++) {
8596 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 multiple rthdr"));
8597 				REASON_SET(reason, PFRES_IPOPTIONS);
8598 				return (PF_DROP);
8599 			}
8600 			if (!pf_pull_hdr(m, *off, &rthdr, sizeof(rthdr), NULL,
8601 				reason, AF_INET6)) {
8602 				/* fragments may be short */
8603 				if (*fragoff != 0) {
8604 					*off = *fragoff;
8605 					*nxt = IPPROTO_FRAGMENT;
8606 					return (PF_PASS);
8607 				}
8608 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short rthdr"));
8609 				return (PF_DROP);
8610 			}
8611 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
8612 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 rthdr0"));
8613 				REASON_SET(reason, PFRES_IPOPTIONS);
8614 				return (PF_DROP);
8615 			}
8616 			/* FALLTHROUGH */
8617 		case IPPROTO_AH:
8618 		case IPPROTO_HOPOPTS:
8619 		case IPPROTO_DSTOPTS:
8620 			if (!pf_pull_hdr(m, *off, &ext, sizeof(ext), NULL,
8621 				reason, AF_INET6)) {
8622 				/* fragments may be short */
8623 				if (*fragoff != 0) {
8624 					*off = *fragoff;
8625 					*nxt = IPPROTO_FRAGMENT;
8626 					return (PF_PASS);
8627 				}
8628 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short exthdr"));
8629 				return (PF_DROP);
8630 			}
8631 			/* reassembly needs the ext header before the frag */
8632 			if (*fragoff == 0)
8633 				*extoff = *off;
8634 			if (*nxt == IPPROTO_HOPOPTS && *fragoff == 0) {
8635 				if (pf_walk_option6(m, *off + sizeof(ext),
8636 					*off + (ext.ip6e_len + 1) * 8, jumbolen,
8637 					reason) != PF_PASS)
8638 					return (PF_DROP);
8639 				if (ntohs(h->ip6_plen) == 0 && *jumbolen != 0) {
8640 					DPFPRINTF(PF_DEBUG_MISC,
8641 					    ("IPv6 missing jumbo"));
8642 					REASON_SET(reason, PFRES_IPOPTIONS);
8643 					return (PF_DROP);
8644 				}
8645 			}
8646 			if (*nxt == IPPROTO_AH)
8647 				*off += (ext.ip6e_len + 2) * 4;
8648 			else
8649 				*off += (ext.ip6e_len + 1) * 8;
8650 			*nxt = ext.ip6e_nxt;
8651 			break;
8652 		case IPPROTO_TCP:
8653 		case IPPROTO_UDP:
8654 		case IPPROTO_SCTP:
8655 		case IPPROTO_ICMPV6:
8656 			/* fragments may be short, ignore inner header then */
8657 			if (*fragoff != 0 && ntohs(h->ip6_plen) < *off +
8658 			    (*nxt == IPPROTO_TCP ? sizeof(struct tcphdr) :
8659 			    *nxt == IPPROTO_UDP ? sizeof(struct udphdr) :
8660 			    *nxt == IPPROTO_SCTP ? sizeof(struct sctphdr) :
8661 			    sizeof(struct icmp6_hdr))) {
8662 				*off = *fragoff;
8663 				*nxt = IPPROTO_FRAGMENT;
8664 			}
8665 			/* FALLTHROUGH */
8666 		default:
8667 			return (PF_PASS);
8668 		}
8669 	}
8670 }
8671 #endif
8672 
8673 static void
pf_init_pdesc(struct pf_pdesc * pd,struct mbuf * m)8674 pf_init_pdesc(struct pf_pdesc *pd, struct mbuf *m)
8675 {
8676 	memset(pd, 0, sizeof(*pd));
8677 	pd->pf_mtag = pf_find_mtag(m);
8678 	pd->m = m;
8679 }
8680 
8681 static int
pf_setup_pdesc(sa_family_t af,int dir,struct pf_pdesc * pd,struct mbuf ** m0,u_short * action,u_short * reason,struct pfi_kkif * kif,struct pf_rule_actions * default_actions)8682 pf_setup_pdesc(sa_family_t af, int dir, struct pf_pdesc *pd, struct mbuf **m0,
8683     u_short *action, u_short *reason, struct pfi_kkif *kif,
8684     struct pf_rule_actions *default_actions)
8685 {
8686 	pd->af = af;
8687 	pd->dir = dir;
8688 	pd->kif = kif;
8689 	pd->m = *m0;
8690 	pd->sidx = (dir == PF_IN) ? 0 : 1;
8691 	pd->didx = (dir == PF_IN) ? 1 : 0;
8692 
8693 	TAILQ_INIT(&pd->sctp_multihome_jobs);
8694 	if (default_actions != NULL)
8695 		memcpy(&pd->act, default_actions, sizeof(pd->act));
8696 
8697 	if (pd->pf_mtag && pd->pf_mtag->dnpipe) {
8698 		pd->act.dnpipe = pd->pf_mtag->dnpipe;
8699 		pd->act.flags = pd->pf_mtag->dnflags;
8700 	}
8701 
8702 	switch (af) {
8703 #ifdef INET
8704 	case AF_INET: {
8705 		struct ip *h;
8706 
8707 		if (__predict_false((*m0)->m_len < sizeof(struct ip)) &&
8708 		    (pd->m = *m0 = m_pullup(*m0, sizeof(struct ip))) == NULL) {
8709 			DPFPRINTF(PF_DEBUG_URGENT,
8710 			    ("pf_test: m_len < sizeof(struct ip), pullup failed\n"));
8711 			*action = PF_DROP;
8712 			REASON_SET(reason, PFRES_SHORT);
8713 			return (-1);
8714 		}
8715 
8716 		if (pf_normalize_ip(m0, reason, pd) != PF_PASS) {
8717 			/* We do IP header normalization and packet reassembly here */
8718 			*action = PF_DROP;
8719 			return (-1);
8720 		}
8721 		pd->m = *m0;
8722 
8723 		h = mtod(pd->m, struct ip *);
8724 		pd->off = h->ip_hl << 2;
8725 		if (pd->off < (int)sizeof(*h)) {
8726 			*action = PF_DROP;
8727 			REASON_SET(reason, PFRES_SHORT);
8728 			return (-1);
8729 		}
8730 		pd->src = (struct pf_addr *)&h->ip_src;
8731 		pd->dst = (struct pf_addr *)&h->ip_dst;
8732 		pd->ip_sum = &h->ip_sum;
8733 		pd->proto_sum = NULL;
8734 		pd->virtual_proto = pd->proto = h->ip_p;
8735 		pd->tos = h->ip_tos;
8736 		pd->ttl = h->ip_ttl;
8737 		pd->tot_len = ntohs(h->ip_len);
8738 		pd->act.rtableid = -1;
8739 
8740 		if (h->ip_hl > 5)	/* has options */
8741 			pd->badopts++;
8742 
8743 		if (h->ip_off & htons(IP_MF | IP_OFFMASK))
8744 			pd->virtual_proto = PF_VPROTO_FRAGMENT;
8745 
8746 		break;
8747 	}
8748 #endif
8749 #ifdef INET6
8750 	case AF_INET6: {
8751 		struct ip6_hdr *h;
8752 		int fragoff;
8753 		uint32_t jumbolen;
8754 		uint8_t nxt;
8755 
8756 		if (__predict_false((*m0)->m_len < sizeof(struct ip6_hdr)) &&
8757 		    (pd->m = *m0 = m_pullup(*m0, sizeof(struct ip6_hdr))) == NULL) {
8758 			DPFPRINTF(PF_DEBUG_URGENT,
8759 			    ("pf_test6: m_len < sizeof(struct ip6_hdr)"
8760 			     ", pullup failed\n"));
8761 			*action = PF_DROP;
8762 			REASON_SET(reason, PFRES_SHORT);
8763 			return (-1);
8764 		}
8765 
8766 		h = mtod(pd->m, struct ip6_hdr *);
8767 		pd->off = 0;
8768 		if (pf_walk_header6(pd->m, h, &pd->off, &pd->extoff, &fragoff, &nxt,
8769 		    &jumbolen, reason) != PF_PASS) {
8770 			*action = PF_DROP;
8771 			return (-1);
8772 		}
8773 
8774 		h = mtod(pd->m, struct ip6_hdr *);
8775 		pd->src = (struct pf_addr *)&h->ip6_src;
8776 		pd->dst = (struct pf_addr *)&h->ip6_dst;
8777 		pd->ip_sum = NULL;
8778 		pd->proto_sum = NULL;
8779 		pd->tos = IPV6_DSCP(h);
8780 		pd->ttl = h->ip6_hlim;
8781 		pd->tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
8782 		pd->virtual_proto = pd->proto = h->ip6_nxt;
8783 		pd->act.rtableid = -1;
8784 
8785 		if (fragoff != 0)
8786 			pd->virtual_proto = PF_VPROTO_FRAGMENT;
8787 
8788 		/*
8789 		 * we do not support jumbogram.  if we keep going, zero ip6_plen
8790 		 * will do something bad, so drop the packet for now.
8791 		 */
8792 		if (htons(h->ip6_plen) == 0) {
8793 			*action = PF_DROP;
8794 			return (-1);
8795 		}
8796 
8797 		/* We do IP header normalization and packet reassembly here */
8798 		if (pf_normalize_ip6(m0, fragoff, reason, pd) !=
8799 		    PF_PASS) {
8800 			*action = PF_DROP;
8801 			return (-1);
8802 		}
8803 		pd->m = *m0;
8804 		if (pd->m == NULL) {
8805 			/* packet sits in reassembly queue, no error */
8806 			*action = PF_PASS;
8807 			return (-1);
8808 		}
8809 
8810 		/* Update pointers into the packet. */
8811 		h = mtod(pd->m, struct ip6_hdr *);
8812 		pd->src = (struct pf_addr *)&h->ip6_src;
8813 		pd->dst = (struct pf_addr *)&h->ip6_dst;
8814 
8815 		/*
8816 		 * Reassembly may have changed the next protocol from fragment
8817 		 * to something else, so update.
8818 		 */
8819 		pd->virtual_proto = pd->proto = h->ip6_nxt;
8820 		pd->off = 0;
8821 
8822 		if (pf_walk_header6(pd->m, h, &pd->off, &pd->extoff, &fragoff, &nxt,
8823 			&jumbolen, reason) != PF_PASS) {
8824 			*action = PF_DROP;
8825 			return (-1);
8826 		}
8827 
8828 		if (fragoff != 0)
8829 			pd->virtual_proto = PF_VPROTO_FRAGMENT;
8830 
8831 		break;
8832 	}
8833 #endif
8834 	default:
8835 		panic("pf_setup_pdesc called with illegal af %u", af);
8836 	}
8837 
8838 	switch (pd->virtual_proto) {
8839 	case IPPROTO_TCP: {
8840 		struct tcphdr *th = &pd->hdr.tcp;
8841 
8842 		if (!pf_pull_hdr(pd->m, pd->off, th, sizeof(*th), action,
8843 			reason, af)) {
8844 			*action = PF_DROP;
8845 			REASON_SET(reason, PFRES_SHORT);
8846 			return (-1);
8847 		}
8848 		pd->hdrlen = sizeof(*th);
8849 		pd->p_len = pd->tot_len - pd->off - (th->th_off << 2);
8850 		pd->sport = &th->th_sport;
8851 		pd->dport = &th->th_dport;
8852 		break;
8853 	}
8854 	case IPPROTO_UDP: {
8855 		struct udphdr *uh = &pd->hdr.udp;
8856 
8857 		if (!pf_pull_hdr(pd->m, pd->off, uh, sizeof(*uh), action,
8858 			reason, af)) {
8859 			*action = PF_DROP;
8860 			REASON_SET(reason, PFRES_SHORT);
8861 			return (-1);
8862 		}
8863 		pd->hdrlen = sizeof(*uh);
8864 		if (uh->uh_dport == 0 ||
8865 		    ntohs(uh->uh_ulen) > pd->m->m_pkthdr.len - pd->off ||
8866 		    ntohs(uh->uh_ulen) < sizeof(struct udphdr)) {
8867 			*action = PF_DROP;
8868 			REASON_SET(reason, PFRES_SHORT);
8869 			return (-1);
8870 		}
8871 		pd->sport = &uh->uh_sport;
8872 		pd->dport = &uh->uh_dport;
8873 		break;
8874 	}
8875 	case IPPROTO_SCTP: {
8876 		if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.sctp, sizeof(pd->hdr.sctp),
8877 		    action, reason, af)) {
8878 			*action = PF_DROP;
8879 			REASON_SET(reason, PFRES_SHORT);
8880 			return (-1);
8881 		}
8882 		pd->hdrlen = sizeof(pd->hdr.sctp);
8883 		pd->p_len = pd->tot_len - pd->off;
8884 
8885 		pd->sport = &pd->hdr.sctp.src_port;
8886 		pd->dport = &pd->hdr.sctp.dest_port;
8887 		if (pd->hdr.sctp.src_port == 0 || pd->hdr.sctp.dest_port == 0) {
8888 			*action = PF_DROP;
8889 			REASON_SET(reason, PFRES_SHORT);
8890 			return (-1);
8891 		}
8892 		if (pf_scan_sctp(pd) != PF_PASS) {
8893 			*action = PF_DROP;
8894 			REASON_SET(reason, PFRES_SHORT);
8895 			return (-1);
8896 		}
8897 		break;
8898 	}
8899 	case IPPROTO_ICMP: {
8900 		if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp, ICMP_MINLEN,
8901 			action, reason, af)) {
8902 			*action = PF_DROP;
8903 			REASON_SET(reason, PFRES_SHORT);
8904 			return (-1);
8905 		}
8906 		pd->hdrlen = ICMP_MINLEN;
8907 		break;
8908 	}
8909 #ifdef INET6
8910 	case IPPROTO_ICMPV6: {
8911 		size_t icmp_hlen = sizeof(struct icmp6_hdr);
8912 
8913 		if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
8914 			action, reason, af)) {
8915 			*action = PF_DROP;
8916 			REASON_SET(reason, PFRES_SHORT);
8917 			return (-1);
8918 		}
8919 		/* ICMP headers we look further into to match state */
8920 		switch (pd->hdr.icmp6.icmp6_type) {
8921 		case MLD_LISTENER_QUERY:
8922 		case MLD_LISTENER_REPORT:
8923 			icmp_hlen = sizeof(struct mld_hdr);
8924 			break;
8925 		case ND_NEIGHBOR_SOLICIT:
8926 		case ND_NEIGHBOR_ADVERT:
8927 			icmp_hlen = sizeof(struct nd_neighbor_solicit);
8928 			break;
8929 		}
8930 		if (icmp_hlen > sizeof(struct icmp6_hdr) &&
8931 		    !pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
8932 			action, reason, af)) {
8933 			*action = PF_DROP;
8934 			REASON_SET(reason, PFRES_SHORT);
8935 			return (-1);
8936 		}
8937 		pd->hdrlen = icmp_hlen;
8938 		break;
8939 	}
8940 #endif
8941 	}
8942 	return (0);
8943 }
8944 
8945 static void
pf_counters_inc(int action,struct pf_pdesc * pd,struct pf_kstate * s,struct pf_krule * r,struct pf_krule * a)8946 pf_counters_inc(int action, struct pf_pdesc *pd,
8947     struct pf_kstate *s, struct pf_krule *r, struct pf_krule *a)
8948 {
8949 	struct pf_krule		*tr;
8950 	int			 dir = pd->dir;
8951 	int			 dirndx;
8952 
8953 	pf_counter_u64_critical_enter();
8954 	pf_counter_u64_add_protected(
8955 	    &pd->kif->pfik_bytes[pd->af == AF_INET6][dir == PF_OUT][action != PF_PASS],
8956 	    pd->tot_len);
8957 	pf_counter_u64_add_protected(
8958 	    &pd->kif->pfik_packets[pd->af == AF_INET6][dir == PF_OUT][action != PF_PASS],
8959 	    1);
8960 
8961 	if (action == PF_PASS || r->action == PF_DROP) {
8962 		dirndx = (dir == PF_OUT);
8963 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
8964 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd->tot_len);
8965 		pf_update_timestamp(r);
8966 
8967 		if (a != NULL) {
8968 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
8969 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd->tot_len);
8970 		}
8971 		if (s != NULL) {
8972 			struct pf_krule_item	*ri;
8973 
8974 			if (s->nat_rule != NULL) {
8975 				pf_counter_u64_add_protected(&s->nat_rule->packets[dirndx],
8976 				    1);
8977 				pf_counter_u64_add_protected(&s->nat_rule->bytes[dirndx],
8978 				    pd->tot_len);
8979 			}
8980 			if (s->src_node != NULL) {
8981 				counter_u64_add(s->src_node->packets[dirndx],
8982 				    1);
8983 				counter_u64_add(s->src_node->bytes[dirndx],
8984 				    pd->tot_len);
8985 			}
8986 			if (s->nat_src_node != NULL) {
8987 				counter_u64_add(s->nat_src_node->packets[dirndx],
8988 				    1);
8989 				counter_u64_add(s->nat_src_node->bytes[dirndx],
8990 				    pd->tot_len);
8991 			}
8992 			dirndx = (dir == s->direction) ? 0 : 1;
8993 			s->packets[dirndx]++;
8994 			s->bytes[dirndx] += pd->tot_len;
8995 
8996 			SLIST_FOREACH(ri, &s->match_rules, entry) {
8997 				pf_counter_u64_add_protected(&ri->r->packets[dirndx], 1);
8998 				pf_counter_u64_add_protected(&ri->r->bytes[dirndx], pd->tot_len);
8999 			}
9000 		}
9001 
9002 		tr = r;
9003 		if (s != NULL && s->nat_rule != NULL &&
9004 		    r == &V_pf_default_rule)
9005 			tr = s->nat_rule;
9006 
9007 		if (tr->src.addr.type == PF_ADDR_TABLE)
9008 			pfr_update_stats(tr->src.addr.p.tbl,
9009 			    (s == NULL) ? pd->src :
9010 			    &s->key[(s->direction == PF_IN)]->
9011 				addr[(s->direction == PF_OUT)],
9012 			    pd->af, pd->tot_len, dir == PF_OUT,
9013 			    r->action == PF_PASS, tr->src.neg);
9014 		if (tr->dst.addr.type == PF_ADDR_TABLE)
9015 			pfr_update_stats(tr->dst.addr.p.tbl,
9016 			    (s == NULL) ? pd->dst :
9017 			    &s->key[(s->direction == PF_IN)]->
9018 				addr[(s->direction == PF_IN)],
9019 			    pd->af, pd->tot_len, dir == PF_OUT,
9020 			    r->action == PF_PASS, tr->dst.neg);
9021 	}
9022 	pf_counter_u64_critical_exit();
9023 }
9024 
9025 #if defined(INET) || defined(INET6)
9026 int
pf_test(sa_family_t af,int dir,int pflags,struct ifnet * ifp,struct mbuf ** m0,struct inpcb * inp,struct pf_rule_actions * default_actions)9027 pf_test(sa_family_t af, int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
9028     struct inpcb *inp, struct pf_rule_actions *default_actions)
9029 {
9030 	struct pfi_kkif		*kif;
9031 	u_short			 action, reason = 0;
9032 	struct m_tag		*mtag;
9033 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule;
9034 	struct pf_kstate	*s = NULL;
9035 	struct pf_kruleset	*ruleset = NULL;
9036 	struct pf_pdesc		 pd;
9037 	int			 use_2nd_queue = 0;
9038 	uint16_t		 tag;
9039 	uint8_t			 rt;
9040 
9041 	PF_RULES_RLOCK_TRACKER;
9042 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
9043 	M_ASSERTPKTHDR(*m0);
9044 
9045 	if (!V_pf_status.running)
9046 		return (PF_PASS);
9047 
9048 	PF_RULES_RLOCK();
9049 
9050 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
9051 
9052 	if (__predict_false(kif == NULL)) {
9053 		DPFPRINTF(PF_DEBUG_URGENT,
9054 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
9055 		PF_RULES_RUNLOCK();
9056 		return (PF_DROP);
9057 	}
9058 	if (kif->pfik_flags & PFI_IFLAG_SKIP) {
9059 		PF_RULES_RUNLOCK();
9060 		return (PF_PASS);
9061 	}
9062 
9063 	if ((*m0)->m_flags & M_SKIP_FIREWALL) {
9064 		PF_RULES_RUNLOCK();
9065 		return (PF_PASS);
9066 	}
9067 
9068 #ifdef INET6
9069 	/*
9070 	 * If we end up changing IP addresses (e.g. binat) the stack may get
9071 	 * confused and fail to send the icmp6 packet too big error. Just send
9072 	 * it here, before we do any NAT.
9073 	 */
9074 	if (af == AF_INET6 && dir == PF_OUT && pflags & PFIL_FWD &&
9075 	    IN6_LINKMTU(ifp) < pf_max_frag_size(*m0)) {
9076 		PF_RULES_RUNLOCK();
9077 		icmp6_error(*m0, ICMP6_PACKET_TOO_BIG, 0, IN6_LINKMTU(ifp));
9078 		*m0 = NULL;
9079 		return (PF_DROP);
9080 	}
9081 #endif
9082 
9083 	if (__predict_false(! M_WRITABLE(*m0))) {
9084 		*m0 = m_unshare(*m0, M_NOWAIT);
9085 		if (*m0 == NULL) {
9086 			PF_RULES_RUNLOCK();
9087 			return (PF_DROP);
9088 		}
9089 	}
9090 
9091 	pf_init_pdesc(&pd, *m0);
9092 
9093 	if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_MTAG_FLAG_ROUTE_TO)) {
9094 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
9095 
9096 		ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
9097 		    pd.pf_mtag->if_idxgen);
9098 		if (ifp == NULL || ifp->if_flags & IFF_DYING) {
9099 			PF_RULES_RUNLOCK();
9100 			m_freem(*m0);
9101 			*m0 = NULL;
9102 			return (PF_PASS);
9103 		}
9104 		PF_RULES_RUNLOCK();
9105 		(ifp->if_output)(ifp, *m0, sintosa(&pd.pf_mtag->dst), NULL);
9106 		*m0 = NULL;
9107 		return (PF_PASS);
9108 	}
9109 
9110 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
9111 	    pd.pf_mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
9112 		/* Dummynet re-injects packets after they've
9113 		 * completed their delay. We've already
9114 		 * processed them, so pass unconditionally. */
9115 
9116 		/* But only once. We may see the packet multiple times (e.g.
9117 		 * PFIL_IN/PFIL_OUT). */
9118 		pf_dummynet_flag_remove(pd.m, pd.pf_mtag);
9119 		PF_RULES_RUNLOCK();
9120 
9121 		return (PF_PASS);
9122 	}
9123 
9124 	if (pf_setup_pdesc(af, dir, &pd, m0, &action, &reason,
9125 		kif, default_actions) == -1) {
9126 		if (action != PF_PASS)
9127 			pd.act.log |= PF_LOG_FORCE;
9128 		goto done;
9129 	}
9130 
9131 	if (__predict_false(ip_divert_ptr != NULL) &&
9132 	    ((mtag = m_tag_locate(pd.m, MTAG_PF_DIVERT, 0, NULL)) != NULL)) {
9133 		struct pf_divert_mtag *dt = (struct pf_divert_mtag *)(mtag+1);
9134 		if ((dt->idir == PF_DIVERT_MTAG_DIR_IN && dir == PF_IN) ||
9135 		    (dt->idir == PF_DIVERT_MTAG_DIR_OUT && dir == PF_OUT)) {
9136 			if (pd.pf_mtag == NULL &&
9137 			    ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
9138 				action = PF_DROP;
9139 				goto done;
9140 			}
9141 			pd.pf_mtag->flags |= PF_MTAG_FLAG_PACKET_LOOPED;
9142 		}
9143 		if (pd.pf_mtag && pd.pf_mtag->flags & PF_MTAG_FLAG_FASTFWD_OURS_PRESENT) {
9144 			pd.m->m_flags |= M_FASTFWD_OURS;
9145 			pd.pf_mtag->flags &= ~PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
9146 		}
9147 		m_tag_delete(pd.m, mtag);
9148 
9149 		mtag = m_tag_locate(pd.m, MTAG_IPFW_RULE, 0, NULL);
9150 		if (mtag != NULL)
9151 			m_tag_delete(pd.m, mtag);
9152 	}
9153 
9154 	switch (pd.virtual_proto) {
9155 	case PF_VPROTO_FRAGMENT:
9156 		/*
9157 		 * handle fragments that aren't reassembled by
9158 		 * normalization
9159 		 */
9160 		if (kif == NULL || r == NULL) /* pflog */
9161 			action = PF_DROP;
9162 		else
9163 			action = pf_test_rule(&r, &s, &pd, &a,
9164 			    &ruleset, inp);
9165 		if (action != PF_PASS)
9166 			REASON_SET(&reason, PFRES_FRAG);
9167 		break;
9168 
9169 	case IPPROTO_TCP: {
9170 		/* Respond to SYN with a syncookie. */
9171 		if ((tcp_get_flags(&pd.hdr.tcp) & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
9172 		    pd.dir == PF_IN && pf_synflood_check(&pd)) {
9173 			pf_syncookie_send(&pd);
9174 			action = PF_DROP;
9175 			break;
9176 		}
9177 
9178 		if ((tcp_get_flags(&pd.hdr.tcp) & TH_ACK) && pd.p_len == 0)
9179 			use_2nd_queue = 1;
9180 		action = pf_normalize_tcp(&pd);
9181 		if (action == PF_DROP)
9182 			goto done;
9183 		action = pf_test_state_tcp(&s, &pd, &reason);
9184 		if (action == PF_PASS) {
9185 			if (V_pfsync_update_state_ptr != NULL)
9186 				V_pfsync_update_state_ptr(s);
9187 			r = s->rule;
9188 			a = s->anchor;
9189 		} else if (s == NULL) {
9190 			/* Validate remote SYN|ACK, re-create original SYN if
9191 			 * valid. */
9192 			if ((tcp_get_flags(&pd.hdr.tcp) & (TH_SYN|TH_ACK|TH_RST)) ==
9193 			    TH_ACK && pf_syncookie_validate(&pd) &&
9194 			    pd.dir == PF_IN) {
9195 				struct mbuf *msyn;
9196 
9197 				msyn = pf_syncookie_recreate_syn(&pd);
9198 				if (msyn == NULL) {
9199 					action = PF_DROP;
9200 					break;
9201 				}
9202 
9203 				action = pf_test(af, dir, pflags, ifp, &msyn, inp,
9204 				    &pd.act);
9205 				m_freem(msyn);
9206 				if (action != PF_PASS)
9207 					break;
9208 
9209 				action = pf_test_state_tcp(&s, &pd, &reason);
9210 				if (action != PF_PASS || s == NULL) {
9211 					action = PF_DROP;
9212 					break;
9213 				}
9214 
9215 				s->src.seqhi = ntohl(pd.hdr.tcp.th_ack) - 1;
9216 				s->src.seqlo = ntohl(pd.hdr.tcp.th_seq) - 1;
9217 				pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_DST);
9218 				action = pf_synproxy(&pd, &s, &reason);
9219 				break;
9220 			} else {
9221 				action = pf_test_rule(&r, &s, &pd,
9222 				    &a, &ruleset, inp);
9223 			}
9224 		}
9225 		break;
9226 	}
9227 
9228 	case IPPROTO_UDP: {
9229 		action = pf_test_state_udp(&s, &pd);
9230 		if (action == PF_PASS) {
9231 			if (V_pfsync_update_state_ptr != NULL)
9232 				V_pfsync_update_state_ptr(s);
9233 			r = s->rule;
9234 			a = s->anchor;
9235 		} else if (s == NULL)
9236 			action = pf_test_rule(&r, &s, &pd,
9237 			    &a, &ruleset, inp);
9238 		break;
9239 	}
9240 
9241 	case IPPROTO_SCTP: {
9242 		action = pf_normalize_sctp(&pd);
9243 		if (action == PF_DROP)
9244 			goto done;
9245 		action = pf_test_state_sctp(&s, &pd, &reason);
9246 		if (action == PF_PASS) {
9247 			if (V_pfsync_update_state_ptr != NULL)
9248 				V_pfsync_update_state_ptr(s);
9249 			r = s->rule;
9250 			a = s->anchor;
9251 		} else if (s == NULL) {
9252 			action = pf_test_rule(&r, &s,
9253 			    &pd, &a, &ruleset, inp);
9254 		}
9255 		break;
9256 	}
9257 
9258 	case IPPROTO_ICMP: {
9259 		if (af != AF_INET) {
9260 			action = PF_DROP;
9261 			REASON_SET(&reason, PFRES_NORM);
9262 			DPFPRINTF(PF_DEBUG_MISC,
9263 			    ("dropping IPv6 packet with ICMPv4 payload"));
9264 			goto done;
9265 		}
9266 		action = pf_test_state_icmp(&s, &pd, &reason);
9267 		if (action == PF_PASS) {
9268 			if (V_pfsync_update_state_ptr != NULL)
9269 				V_pfsync_update_state_ptr(s);
9270 			r = s->rule;
9271 			a = s->anchor;
9272 		} else if (s == NULL)
9273 			action = pf_test_rule(&r, &s, &pd,
9274 			    &a, &ruleset, inp);
9275 		break;
9276 	}
9277 
9278 	case IPPROTO_ICMPV6: {
9279 		if (af != AF_INET6) {
9280 			action = PF_DROP;
9281 			REASON_SET(&reason, PFRES_NORM);
9282 			DPFPRINTF(PF_DEBUG_MISC,
9283 			    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
9284 			goto done;
9285 		}
9286 		action = pf_test_state_icmp(&s, &pd, &reason);
9287 		if (action == PF_PASS) {
9288 			if (V_pfsync_update_state_ptr != NULL)
9289 				V_pfsync_update_state_ptr(s);
9290 			r = s->rule;
9291 			a = s->anchor;
9292 		} else if (s == NULL)
9293 			action = pf_test_rule(&r, &s, &pd,
9294 			    &a, &ruleset, inp);
9295 		break;
9296 	}
9297 
9298 	default:
9299 		action = pf_test_state_other(&s, &pd);
9300 		if (action == PF_PASS) {
9301 			if (V_pfsync_update_state_ptr != NULL)
9302 				V_pfsync_update_state_ptr(s);
9303 			r = s->rule;
9304 			a = s->anchor;
9305 		} else if (s == NULL)
9306 			action = pf_test_rule(&r, &s, &pd,
9307 			    &a, &ruleset, inp);
9308 		break;
9309 	}
9310 
9311 done:
9312 	PF_RULES_RUNLOCK();
9313 
9314 	if (pd.m == NULL)
9315 		goto eat_pkt;
9316 
9317 	if (action == PF_PASS && pd.badopts &&
9318 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
9319 		action = PF_DROP;
9320 		REASON_SET(&reason, PFRES_IPOPTIONS);
9321 		pd.act.log = PF_LOG_FORCE;
9322 		DPFPRINTF(PF_DEBUG_MISC,
9323 		    ("pf: dropping packet with dangerous headers\n"));
9324 	}
9325 
9326 	if (s) {
9327 		uint8_t log = pd.act.log;
9328 		memcpy(&pd.act, &s->act, sizeof(struct pf_rule_actions));
9329 		pd.act.log |= log;
9330 		tag = s->tag;
9331 		rt = s->rt;
9332 	} else {
9333 		tag = r->tag;
9334 		rt = r->rt;
9335 	}
9336 
9337 	if (tag > 0 && pf_tag_packet(&pd, tag)) {
9338 		action = PF_DROP;
9339 		REASON_SET(&reason, PFRES_MEMORY);
9340 	}
9341 
9342 	pf_scrub(&pd);
9343 	if (pd.proto == IPPROTO_TCP && pd.act.max_mss)
9344 		pf_normalize_mss(&pd);
9345 
9346 	if (pd.act.rtableid >= 0)
9347 		M_SETFIB(pd.m, pd.act.rtableid);
9348 
9349 	if (pd.act.flags & PFSTATE_SETPRIO) {
9350 		if (pd.tos & IPTOS_LOWDELAY)
9351 			use_2nd_queue = 1;
9352 		if (vlan_set_pcp(pd.m, pd.act.set_prio[use_2nd_queue])) {
9353 			action = PF_DROP;
9354 			REASON_SET(&reason, PFRES_MEMORY);
9355 			pd.act.log = PF_LOG_FORCE;
9356 			DPFPRINTF(PF_DEBUG_MISC,
9357 			    ("pf: failed to allocate 802.1q mtag\n"));
9358 		}
9359 	}
9360 
9361 #ifdef ALTQ
9362 	if (action == PF_PASS && pd.act.qid) {
9363 		if (pd.pf_mtag == NULL &&
9364 		    ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
9365 			action = PF_DROP;
9366 			REASON_SET(&reason, PFRES_MEMORY);
9367 		} else {
9368 			if (s != NULL)
9369 				pd.pf_mtag->qid_hash = pf_state_hash(s);
9370 			if (use_2nd_queue || (pd.tos & IPTOS_LOWDELAY))
9371 				pd.pf_mtag->qid = pd.act.pqid;
9372 			else
9373 				pd.pf_mtag->qid = pd.act.qid;
9374 			/* Add hints for ecn. */
9375 			pd.pf_mtag->hdr = mtod(pd.m, void *);
9376 		}
9377 	}
9378 #endif /* ALTQ */
9379 
9380 	/*
9381 	 * connections redirected to loopback should not match sockets
9382 	 * bound specifically to loopback due to security implications,
9383 	 * see tcp_input() and in_pcblookup_listen().
9384 	 */
9385 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
9386 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule != NULL &&
9387 	    (s->nat_rule->action == PF_RDR ||
9388 	    s->nat_rule->action == PF_BINAT) &&
9389 	    pf_is_loopback(af, pd.dst))
9390 		pd.m->m_flags |= M_SKIP_FIREWALL;
9391 
9392 	if (af == AF_INET && __predict_false(ip_divert_ptr != NULL) &&
9393 	    action == PF_PASS && r->divert.port && !PACKET_LOOPED(&pd)) {
9394 		mtag = m_tag_alloc(MTAG_PF_DIVERT, 0,
9395 		    sizeof(struct pf_divert_mtag), M_NOWAIT | M_ZERO);
9396 		if (mtag != NULL) {
9397 			((struct pf_divert_mtag *)(mtag+1))->port =
9398 			    ntohs(r->divert.port);
9399 			((struct pf_divert_mtag *)(mtag+1))->idir =
9400 			    (dir == PF_IN) ? PF_DIVERT_MTAG_DIR_IN :
9401 			    PF_DIVERT_MTAG_DIR_OUT;
9402 
9403 			if (s)
9404 				PF_STATE_UNLOCK(s);
9405 
9406 			m_tag_prepend(pd.m, mtag);
9407 			if (pd.m->m_flags & M_FASTFWD_OURS) {
9408 				if (pd.pf_mtag == NULL &&
9409 				    ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
9410 					action = PF_DROP;
9411 					REASON_SET(&reason, PFRES_MEMORY);
9412 					pd.act.log = PF_LOG_FORCE;
9413 					DPFPRINTF(PF_DEBUG_MISC,
9414 					    ("pf: failed to allocate tag\n"));
9415 				} else {
9416 					pd.pf_mtag->flags |=
9417 					    PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
9418 					pd.m->m_flags &= ~M_FASTFWD_OURS;
9419 				}
9420 			}
9421 			ip_divert_ptr(*m0, dir == PF_IN);
9422 			*m0 = NULL;
9423 
9424 			return (action);
9425 		} else {
9426 			/* XXX: ipfw has the same behaviour! */
9427 			action = PF_DROP;
9428 			REASON_SET(&reason, PFRES_MEMORY);
9429 			pd.act.log = PF_LOG_FORCE;
9430 			DPFPRINTF(PF_DEBUG_MISC,
9431 			    ("pf: failed to allocate divert tag\n"));
9432 		}
9433 	}
9434 	/* XXX: Anybody working on it?! */
9435 	if (af == AF_INET6 && r->divert.port)
9436 		printf("pf: divert(9) is not supported for IPv6\n");
9437 
9438 	/* this flag will need revising if the pkt is forwarded */
9439 	if (pd.pf_mtag)
9440 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_PACKET_LOOPED;
9441 
9442 	if (pd.act.log) {
9443 		struct pf_krule		*lr;
9444 		struct pf_krule_item	*ri;
9445 
9446 		if (s != NULL && s->nat_rule != NULL &&
9447 		    s->nat_rule->log & PF_LOG_ALL)
9448 			lr = s->nat_rule;
9449 		else
9450 			lr = r;
9451 
9452 		if (pd.act.log & PF_LOG_FORCE || lr->log & PF_LOG_ALL)
9453 			PFLOG_PACKET(action, reason, lr, a,
9454 			    ruleset, &pd, (s == NULL));
9455 		if (s) {
9456 			SLIST_FOREACH(ri, &s->match_rules, entry)
9457 				if (ri->r->log & PF_LOG_ALL)
9458 					PFLOG_PACKET(action,
9459 					    reason, ri->r, a, ruleset, &pd, 0);
9460 		}
9461 	}
9462 
9463 	pf_counters_inc(action, &pd, s, r, a);
9464 
9465 	switch (action) {
9466 	case PF_SYNPROXY_DROP:
9467 		m_freem(*m0);
9468 	case PF_DEFER:
9469 		*m0 = NULL;
9470 		action = PF_PASS;
9471 		break;
9472 	case PF_DROP:
9473 		m_freem(*m0);
9474 		*m0 = NULL;
9475 		break;
9476 	default:
9477 		if (rt) {
9478 			switch (af) {
9479 #ifdef INET
9480 			case AF_INET:
9481 				/* pf_route() returns unlocked. */
9482 				pf_route(m0, r, kif->pfik_ifp, s, &pd, inp);
9483 				break;
9484 #endif
9485 #ifdef INET6
9486 			case AF_INET6:
9487 				/* pf_route6() returns unlocked. */
9488 				pf_route6(m0, r, kif->pfik_ifp, s, &pd, inp);
9489 				break;
9490 #endif
9491 			}
9492 			goto out;
9493 		}
9494 		if (pf_dummynet(&pd, s, r, m0) != 0) {
9495 			action = PF_DROP;
9496 			REASON_SET(&reason, PFRES_MEMORY);
9497 		}
9498 		break;
9499 	}
9500 
9501 eat_pkt:
9502 	SDT_PROBE4(pf, ip, test, done, action, reason, r, s);
9503 
9504 	if (s && action != PF_DROP) {
9505 		if (!s->if_index_in && dir == PF_IN)
9506 			s->if_index_in = ifp->if_index;
9507 		else if (!s->if_index_out && dir == PF_OUT)
9508 			s->if_index_out = ifp->if_index;
9509 	}
9510 
9511 	if (s)
9512 		PF_STATE_UNLOCK(s);
9513 
9514 out:
9515 #ifdef INET6
9516 	/* If reassembled packet passed, create new fragments. */
9517 	if (af == AF_INET6 && action == PF_PASS && *m0 && dir == PF_OUT &&
9518 	    (! (pflags & PF_PFIL_NOREFRAGMENT)) &&
9519 	    (mtag = m_tag_find(pd.m, PACKET_TAG_PF_REASSEMBLED, NULL)) != NULL)
9520 		action = pf_refragment6(ifp, m0, mtag, NULL, pflags & PFIL_FWD);
9521 #endif
9522 
9523 	pf_sctp_multihome_delayed(&pd, kif, s, action);
9524 
9525 	return (action);
9526 }
9527 #endif /* INET || INET6 */
9528