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