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