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