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