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