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