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