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