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