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