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, 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
7393 if ((tcp_get_flags(th) & TH_ACK) == 0) {
7394 /* Let it pass through the ack skew check */
7395 ack = dst->seqlo;
7396 } else if ((ack == 0 &&
7397 (tcp_get_flags(th) & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
7398 /* broken tcp stacks do not set ack */
7399 (dst->state < TCPS_SYN_SENT)) {
7400 /*
7401 * Many stacks (ours included) will set the ACK number in an
7402 * FIN|ACK if the SYN times out -- no sequence to ACK.
7403 */
7404 ack = dst->seqlo;
7405 }
7406
7407 if (seq == end) {
7408 /* Ease sequencing restrictions on no data packets */
7409 seq = src->seqlo;
7410 data_end = end = seq;
7411 }
7412
7413 ackskew = dst->seqlo - ack;
7414
7415 /*
7416 * Need to demodulate the sequence numbers in any TCP SACK options
7417 * (Selective ACK). We could optionally validate the SACK values
7418 * against the current ACK window, either forwards or backwards, but
7419 * I'm not confident that SACK has been implemented properly
7420 * everywhere. It wouldn't surprise me if several stacks accidentally
7421 * SACK too far backwards of previously ACKed data. There really aren't
7422 * any security implications of bad SACKing unless the target stack
7423 * doesn't validate the option length correctly. Someone trying to
7424 * spoof into a TCP connection won't bother blindly sending SACK
7425 * options anyway.
7426 */
7427 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
7428 if (pf_modulate_sack(pd, th, dst))
7429 *copyback = 1;
7430 }
7431
7432 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
7433 if (SEQ_GEQ(src->seqhi, data_end) &&
7434 /* Last octet inside other's window space */
7435 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
7436 /* Retrans: not more than one window back */
7437 (ackskew >= -MAXACKWINDOW) &&
7438 /* Acking not more than one reassembled fragment backwards */
7439 (ackskew <= (MAXACKWINDOW << sws)) &&
7440 /* Acking not more than one window forward */
7441 ((tcp_get_flags(th) & TH_RST) == 0 || orig_seq == src->seqlo ||
7442 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
7443 /* Require an exact/+1 sequence match on resets when possible */
7444 (SEQ_GEQ(orig_seq, src->seqlo - (dst->max_win << dws)) &&
7445 SEQ_LEQ(orig_seq, src->seqlo + 1) && ackskew == 0 &&
7446 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)))) {
7447 /* Allow resets to match sequence window if ack is perfect match */
7448
7449 if (dst->scrub || src->scrub) {
7450 if (pf_normalize_tcp_stateful(pd, reason, th,
7451 state, src, dst, copyback))
7452 return (PF_DROP);
7453 }
7454
7455 /* update max window */
7456 if (src->max_win < win)
7457 src->max_win = win;
7458 /* synchronize sequencing */
7459 if (SEQ_GT(end, src->seqlo))
7460 src->seqlo = end;
7461 /* slide the window of what the other end can send */
7462 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
7463 dst->seqhi = ack + MAX((win << sws), 1);
7464
7465 /* update states */
7466 if (tcp_get_flags(th) & TH_SYN)
7467 if (src->state < TCPS_SYN_SENT)
7468 pf_set_protostate(state, psrc, TCPS_SYN_SENT);
7469 if (tcp_get_flags(th) & TH_FIN)
7470 if (src->state < TCPS_CLOSING)
7471 pf_set_protostate(state, psrc, TCPS_CLOSING);
7472 if (tcp_get_flags(th) & TH_ACK) {
7473 if (dst->state == TCPS_SYN_SENT) {
7474 pf_set_protostate(state, pdst,
7475 TCPS_ESTABLISHED);
7476 if (src->state == TCPS_ESTABLISHED &&
7477 state->sns[PF_SN_LIMIT] != NULL &&
7478 pf_src_connlimit(state)) {
7479 REASON_SET(reason, PFRES_SRCLIMIT);
7480 return (PF_DROP);
7481 }
7482 } else if (dst->state == TCPS_CLOSING)
7483 pf_set_protostate(state, pdst,
7484 TCPS_FIN_WAIT_2);
7485 }
7486 if (tcp_get_flags(th) & TH_RST)
7487 pf_set_protostate(state, PF_PEER_BOTH, TCPS_TIME_WAIT);
7488
7489 /* update expire time */
7490 state->expire = pf_get_uptime();
7491 if (src->state >= TCPS_FIN_WAIT_2 &&
7492 dst->state >= TCPS_FIN_WAIT_2)
7493 state->timeout = PFTM_TCP_CLOSED;
7494 else if (src->state >= TCPS_CLOSING &&
7495 dst->state >= TCPS_CLOSING)
7496 state->timeout = PFTM_TCP_FIN_WAIT;
7497 else if (src->state < TCPS_ESTABLISHED ||
7498 dst->state < TCPS_ESTABLISHED)
7499 state->timeout = PFTM_TCP_OPENING;
7500 else if (src->state >= TCPS_CLOSING ||
7501 dst->state >= TCPS_CLOSING)
7502 state->timeout = PFTM_TCP_CLOSING;
7503 else
7504 state->timeout = PFTM_TCP_ESTABLISHED;
7505
7506 /* Fall through to PASS packet */
7507
7508 } else if ((dst->state < TCPS_SYN_SENT ||
7509 dst->state >= TCPS_FIN_WAIT_2 ||
7510 src->state >= TCPS_FIN_WAIT_2) &&
7511 SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) &&
7512 /* Within a window forward of the originating packet */
7513 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
7514 /* Within a window backward of the originating packet */
7515
7516 /*
7517 * This currently handles three situations:
7518 * 1) Stupid stacks will shotgun SYNs before their peer
7519 * replies.
7520 * 2) When PF catches an already established stream (the
7521 * firewall rebooted, the state table was flushed, routes
7522 * changed...)
7523 * 3) Packets get funky immediately after the connection
7524 * closes (this should catch Solaris spurious ACK|FINs
7525 * that web servers like to spew after a close)
7526 *
7527 * This must be a little more careful than the above code
7528 * since packet floods will also be caught here. We don't
7529 * update the TTL here to mitigate the damage of a packet
7530 * flood and so the same code can handle awkward establishment
7531 * and a loosened connection close.
7532 * In the establishment case, a correct peer response will
7533 * validate the connection, go through the normal state code
7534 * and keep updating the state TTL.
7535 */
7536
7537 if (V_pf_status.debug >= PF_DEBUG_MISC) {
7538 printf("pf: loose state match: ");
7539 pf_print_state(state);
7540 pf_print_flags(tcp_get_flags(th));
7541 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
7542 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
7543 pd->p_len, ackskew, (unsigned long long)state->packets[0],
7544 (unsigned long long)state->packets[1],
7545 pd->dir == PF_IN ? "in" : "out",
7546 pd->dir == state->direction ? "fwd" : "rev");
7547 }
7548
7549 if (dst->scrub || src->scrub) {
7550 if (pf_normalize_tcp_stateful(pd, reason, th,
7551 state, src, dst, copyback))
7552 return (PF_DROP);
7553 }
7554
7555 /* update max window */
7556 if (src->max_win < win)
7557 src->max_win = win;
7558 /* synchronize sequencing */
7559 if (SEQ_GT(end, src->seqlo))
7560 src->seqlo = end;
7561 /* slide the window of what the other end can send */
7562 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
7563 dst->seqhi = ack + MAX((win << sws), 1);
7564
7565 /*
7566 * Cannot set dst->seqhi here since this could be a shotgunned
7567 * SYN and not an already established connection.
7568 */
7569
7570 if (tcp_get_flags(th) & TH_FIN)
7571 if (src->state < TCPS_CLOSING)
7572 pf_set_protostate(state, psrc, TCPS_CLOSING);
7573 if (tcp_get_flags(th) & TH_RST)
7574 pf_set_protostate(state, PF_PEER_BOTH, TCPS_TIME_WAIT);
7575
7576 /* Fall through to PASS packet */
7577
7578 } else {
7579 if (state->dst.state == TCPS_SYN_SENT &&
7580 state->src.state == TCPS_SYN_SENT) {
7581 /* Send RST for state mismatches during handshake */
7582 if (!(tcp_get_flags(th) & TH_RST))
7583 pf_send_tcp(state->rule, pd->af,
7584 pd->dst, pd->src, th->th_dport,
7585 th->th_sport, ntohl(th->th_ack), 0,
7586 TH_RST, 0, 0,
7587 state->rule->return_ttl, M_SKIP_FIREWALL,
7588 0, 0, state->act.rtableid, reason);
7589 src->seqlo = 0;
7590 src->seqhi = 1;
7591 src->max_win = 1;
7592 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
7593 printf("pf: BAD state: ");
7594 pf_print_state(state);
7595 pf_print_flags(tcp_get_flags(th));
7596 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
7597 "pkts=%llu:%llu dir=%s,%s\n",
7598 seq, orig_seq, ack, pd->p_len, ackskew,
7599 (unsigned long long)state->packets[0],
7600 (unsigned long long)state->packets[1],
7601 pd->dir == PF_IN ? "in" : "out",
7602 pd->dir == state->direction ? "fwd" : "rev");
7603 printf("pf: State failure on: %c %c %c %c | %c %c\n",
7604 SEQ_GEQ(src->seqhi, data_end) ? ' ' : '1',
7605 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
7606 ' ': '2',
7607 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
7608 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
7609 SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) ?' ' :'5',
7610 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
7611 }
7612 REASON_SET(reason, PFRES_BADSTATE);
7613 return (PF_DROP);
7614 }
7615
7616 return (PF_PASS);
7617 }
7618
7619 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)7620 pf_tcp_track_sloppy(struct pf_kstate *state, struct pf_pdesc *pd,
7621 u_short *reason, struct pf_state_peer *src, struct pf_state_peer *dst,
7622 u_int8_t psrc, u_int8_t pdst)
7623 {
7624 struct tcphdr *th = &pd->hdr.tcp;
7625
7626 if (tcp_get_flags(th) & TH_SYN)
7627 if (src->state < TCPS_SYN_SENT)
7628 pf_set_protostate(state, psrc, TCPS_SYN_SENT);
7629 if (tcp_get_flags(th) & TH_FIN)
7630 if (src->state < TCPS_CLOSING)
7631 pf_set_protostate(state, psrc, TCPS_CLOSING);
7632 if (tcp_get_flags(th) & TH_ACK) {
7633 if (dst->state == TCPS_SYN_SENT) {
7634 pf_set_protostate(state, pdst, TCPS_ESTABLISHED);
7635 if (src->state == TCPS_ESTABLISHED &&
7636 state->sns[PF_SN_LIMIT] != NULL &&
7637 pf_src_connlimit(state)) {
7638 REASON_SET(reason, PFRES_SRCLIMIT);
7639 return (PF_DROP);
7640 }
7641 } else if (dst->state == TCPS_CLOSING) {
7642 pf_set_protostate(state, pdst, TCPS_FIN_WAIT_2);
7643 } else if (src->state == TCPS_SYN_SENT &&
7644 dst->state < TCPS_SYN_SENT) {
7645 /*
7646 * Handle a special sloppy case where we only see one
7647 * half of the connection. If there is a ACK after
7648 * the initial SYN without ever seeing a packet from
7649 * the destination, set the connection to established.
7650 */
7651 pf_set_protostate(state, PF_PEER_BOTH,
7652 TCPS_ESTABLISHED);
7653 dst->state = src->state = TCPS_ESTABLISHED;
7654 if (state->sns[PF_SN_LIMIT] != NULL &&
7655 pf_src_connlimit(state)) {
7656 REASON_SET(reason, PFRES_SRCLIMIT);
7657 return (PF_DROP);
7658 }
7659 } else if (src->state == TCPS_CLOSING &&
7660 dst->state == TCPS_ESTABLISHED &&
7661 dst->seqlo == 0) {
7662 /*
7663 * Handle the closing of half connections where we
7664 * don't see the full bidirectional FIN/ACK+ACK
7665 * handshake.
7666 */
7667 pf_set_protostate(state, pdst, TCPS_CLOSING);
7668 }
7669 }
7670 if (tcp_get_flags(th) & TH_RST)
7671 pf_set_protostate(state, PF_PEER_BOTH, TCPS_TIME_WAIT);
7672
7673 /* update expire time */
7674 state->expire = pf_get_uptime();
7675 if (src->state >= TCPS_FIN_WAIT_2 &&
7676 dst->state >= TCPS_FIN_WAIT_2)
7677 state->timeout = PFTM_TCP_CLOSED;
7678 else if (src->state >= TCPS_CLOSING &&
7679 dst->state >= TCPS_CLOSING)
7680 state->timeout = PFTM_TCP_FIN_WAIT;
7681 else if (src->state < TCPS_ESTABLISHED ||
7682 dst->state < TCPS_ESTABLISHED)
7683 state->timeout = PFTM_TCP_OPENING;
7684 else if (src->state >= TCPS_CLOSING ||
7685 dst->state >= TCPS_CLOSING)
7686 state->timeout = PFTM_TCP_CLOSING;
7687 else
7688 state->timeout = PFTM_TCP_ESTABLISHED;
7689
7690 return (PF_PASS);
7691 }
7692
7693 static int
pf_synproxy(struct pf_pdesc * pd,struct pf_kstate * state,u_short * reason)7694 pf_synproxy(struct pf_pdesc *pd, struct pf_kstate *state, u_short *reason)
7695 {
7696 struct pf_state_key *sk = state->key[pd->didx];
7697 struct tcphdr *th = &pd->hdr.tcp;
7698
7699 if (state->src.state == PF_TCPS_PROXY_SRC) {
7700 if (pd->dir != state->direction) {
7701 REASON_SET(reason, PFRES_SYNPROXY);
7702 return (PF_SYNPROXY_DROP);
7703 }
7704 if (tcp_get_flags(th) & TH_SYN) {
7705 if (ntohl(th->th_seq) != state->src.seqlo) {
7706 REASON_SET(reason, PFRES_SYNPROXY);
7707 return (PF_DROP);
7708 }
7709 pf_send_tcp(state->rule, pd->af, pd->dst,
7710 pd->src, th->th_dport, th->th_sport,
7711 state->src.seqhi, ntohl(th->th_seq) + 1,
7712 TH_SYN|TH_ACK, 0, state->src.mss, 0,
7713 M_SKIP_FIREWALL, 0, 0, state->act.rtableid,
7714 reason);
7715 REASON_SET(reason, PFRES_SYNPROXY);
7716 return (PF_SYNPROXY_DROP);
7717 } else if ((tcp_get_flags(th) & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
7718 (ntohl(th->th_ack) != state->src.seqhi + 1) ||
7719 (ntohl(th->th_seq) != state->src.seqlo + 1)) {
7720 REASON_SET(reason, PFRES_SYNPROXY);
7721 return (PF_DROP);
7722 } else if (state->sns[PF_SN_LIMIT] != NULL &&
7723 pf_src_connlimit(state)) {
7724 REASON_SET(reason, PFRES_SRCLIMIT);
7725 return (PF_DROP);
7726 } else
7727 pf_set_protostate(state, PF_PEER_SRC,
7728 PF_TCPS_PROXY_DST);
7729 }
7730 if (state->src.state == PF_TCPS_PROXY_DST) {
7731 if (pd->dir == state->direction) {
7732 if (((tcp_get_flags(th) & (TH_SYN|TH_ACK)) != TH_ACK) ||
7733 (ntohl(th->th_ack) != state->src.seqhi + 1) ||
7734 (ntohl(th->th_seq) != state->src.seqlo + 1)) {
7735 REASON_SET(reason, PFRES_SYNPROXY);
7736 return (PF_DROP);
7737 }
7738 state->src.max_win = MAX(ntohs(th->th_win), 1);
7739 if (state->dst.seqhi == 1)
7740 state->dst.seqhi = arc4random();
7741 pf_send_tcp(state->rule, pd->af,
7742 &sk->addr[pd->sidx], &sk->addr[pd->didx],
7743 sk->port[pd->sidx], sk->port[pd->didx],
7744 state->dst.seqhi, 0, TH_SYN, 0,
7745 state->src.mss, 0,
7746 state->orig_kif->pfik_ifp == V_loif ? M_LOOP : 0,
7747 state->tag, 0, state->act.rtableid,
7748 reason);
7749 REASON_SET(reason, PFRES_SYNPROXY);
7750 return (PF_SYNPROXY_DROP);
7751 } else if (((tcp_get_flags(th) & (TH_SYN|TH_ACK)) !=
7752 (TH_SYN|TH_ACK)) ||
7753 (ntohl(th->th_ack) != state->dst.seqhi + 1)) {
7754 REASON_SET(reason, PFRES_SYNPROXY);
7755 return (PF_DROP);
7756 } else {
7757 state->dst.max_win = MAX(ntohs(th->th_win), 1);
7758 state->dst.seqlo = ntohl(th->th_seq);
7759 pf_send_tcp(state->rule, pd->af, pd->dst,
7760 pd->src, th->th_dport, th->th_sport,
7761 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
7762 TH_ACK, state->src.max_win, 0, 0, 0,
7763 state->tag, 0, state->act.rtableid,
7764 reason);
7765 pf_send_tcp(state->rule, pd->af,
7766 &sk->addr[pd->sidx], &sk->addr[pd->didx],
7767 sk->port[pd->sidx], sk->port[pd->didx],
7768 state->src.seqhi + 1, state->src.seqlo + 1,
7769 TH_ACK, state->dst.max_win, 0, 0,
7770 M_SKIP_FIREWALL, 0, 0, state->act.rtableid,
7771 reason);
7772 state->src.seqdiff = state->dst.seqhi -
7773 state->src.seqlo;
7774 state->dst.seqdiff = state->src.seqhi -
7775 state->dst.seqlo;
7776 state->src.seqhi = state->src.seqlo +
7777 state->dst.max_win;
7778 state->dst.seqhi = state->dst.seqlo +
7779 state->src.max_win;
7780 state->src.wscale = state->dst.wscale = 0;
7781 pf_set_protostate(state, PF_PEER_BOTH,
7782 TCPS_ESTABLISHED);
7783 REASON_SET(reason, PFRES_SYNPROXY);
7784 return (PF_SYNPROXY_DROP);
7785 }
7786 }
7787
7788 return (PF_PASS);
7789 }
7790
7791 static __inline int
pf_synproxy_ack(struct pf_krule * r,struct pf_pdesc * pd,struct pf_kstate ** sm,struct pf_rule_actions * act)7792 pf_synproxy_ack(struct pf_krule *r, struct pf_pdesc *pd, struct pf_kstate **sm,
7793 struct pf_rule_actions *act)
7794 {
7795 struct tcphdr *th = &pd->hdr.tcp;
7796 struct pf_kstate *s;
7797 u_int16_t mss;
7798 int rtid;
7799 u_short reason;
7800
7801 if ((th->th_flags & (TH_SYN | TH_ACK)) != TH_SYN)
7802 return (PF_PASS);
7803
7804 s = *sm;
7805 rtid = act->rtableid;
7806
7807 pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_SRC);
7808 s->src.seqhi = arc4random();
7809 /* Find mss option */
7810 mss = pf_get_mss(pd);
7811 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
7812 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
7813 s->src.mss = mss;
7814
7815 pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
7816 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
7817 TH_SYN | TH_ACK, 0, s->src.mss, 0, 1, 0, 0, r->rtableid, NULL);
7818
7819 REASON_SET(&reason, PFRES_SYNPROXY);
7820 return (PF_SYNPROXY_DROP);
7821 }
7822
7823 static int
pf_test_state(struct pf_kstate ** state,struct pf_pdesc * pd,u_short * reason)7824 pf_test_state(struct pf_kstate **state, struct pf_pdesc *pd, u_short *reason)
7825 {
7826 struct pf_state_key_cmp key;
7827 int copyback = 0;
7828 struct pf_state_peer *src, *dst;
7829 uint8_t psrc, pdst;
7830 int action;
7831
7832 bzero(&key, sizeof(key));
7833 key.af = pd->af;
7834 key.proto = pd->virtual_proto;
7835 pf_addrcpy(&key.addr[pd->sidx], pd->src, key.af);
7836 pf_addrcpy(&key.addr[pd->didx], pd->dst, key.af);
7837 key.port[pd->sidx] = pd->osport;
7838 key.port[pd->didx] = pd->odport;
7839
7840 action = pf_find_state(pd, &key, state);
7841 if (action != PF_MATCH)
7842 return (action);
7843
7844 action = PF_PASS;
7845 if (pd->dir == (*state)->direction) {
7846 if (PF_REVERSED_KEY(*state, pd->af)) {
7847 src = &(*state)->dst;
7848 dst = &(*state)->src;
7849 psrc = PF_PEER_DST;
7850 pdst = PF_PEER_SRC;
7851 } else {
7852 src = &(*state)->src;
7853 dst = &(*state)->dst;
7854 psrc = PF_PEER_SRC;
7855 pdst = PF_PEER_DST;
7856 }
7857 } else {
7858 if (PF_REVERSED_KEY(*state, pd->af)) {
7859 src = &(*state)->src;
7860 dst = &(*state)->dst;
7861 psrc = PF_PEER_SRC;
7862 pdst = PF_PEER_DST;
7863 } else {
7864 src = &(*state)->dst;
7865 dst = &(*state)->src;
7866 psrc = PF_PEER_DST;
7867 pdst = PF_PEER_SRC;
7868 }
7869 }
7870
7871 switch (pd->virtual_proto) {
7872 case IPPROTO_TCP: {
7873 struct tcphdr *th = &pd->hdr.tcp;
7874
7875 if ((action = pf_synproxy(pd, *state, reason)) != PF_PASS)
7876 return (action);
7877 if (((tcp_get_flags(th) & (TH_SYN | TH_ACK)) == TH_SYN) ||
7878 ((th->th_flags & (TH_SYN | TH_ACK | TH_RST)) == TH_ACK &&
7879 pf_syncookie_check(pd) && pd->dir == PF_IN)) {
7880 if ((*state)->src.state >= TCPS_FIN_WAIT_2 &&
7881 (*state)->dst.state >= TCPS_FIN_WAIT_2) {
7882 if (V_pf_status.debug >= PF_DEBUG_MISC) {
7883 printf("pf: state reuse ");
7884 pf_print_state(*state);
7885 pf_print_flags(tcp_get_flags(th));
7886 printf("\n");
7887 }
7888 /* XXX make sure it's the same direction ?? */
7889 pf_set_protostate(*state, PF_PEER_BOTH, TCPS_CLOSED);
7890 pf_remove_state(*state);
7891 *state = NULL;
7892 return (PF_DROP);
7893 } else if ((*state)->src.state >= TCPS_ESTABLISHED &&
7894 (*state)->dst.state >= TCPS_ESTABLISHED) {
7895 /*
7896 * SYN matches existing state???
7897 * Typically happens when sender boots up after
7898 * sudden panic. Certain protocols (NFSv3) are
7899 * always using same port numbers. Challenge
7900 * ACK enables all parties (firewall and peers)
7901 * to get in sync again.
7902 */
7903 pf_send_challenge_ack(pd, *state, src, dst, reason);
7904 return (PF_DROP);
7905 }
7906 }
7907 if ((*state)->state_flags & PFSTATE_SLOPPY) {
7908 if (pf_tcp_track_sloppy(*state, pd, reason, src, dst,
7909 psrc, pdst) == PF_DROP)
7910 return (PF_DROP);
7911 } else {
7912 int ret;
7913
7914 ret = pf_tcp_track_full(*state, pd, reason,
7915 ©back, src, dst, psrc, pdst);
7916 if (ret == PF_DROP)
7917 return (PF_DROP);
7918 }
7919 break;
7920 }
7921 case IPPROTO_UDP:
7922 /* update states */
7923 if (src->state < PFUDPS_SINGLE)
7924 pf_set_protostate(*state, psrc, PFUDPS_SINGLE);
7925 if (dst->state == PFUDPS_SINGLE)
7926 pf_set_protostate(*state, pdst, PFUDPS_MULTIPLE);
7927
7928 /* update expire time */
7929 (*state)->expire = pf_get_uptime();
7930 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
7931 (*state)->timeout = PFTM_UDP_MULTIPLE;
7932 else
7933 (*state)->timeout = PFTM_UDP_SINGLE;
7934 break;
7935 case IPPROTO_SCTP:
7936 if ((src->state >= SCTP_SHUTDOWN_SENT || src->state == SCTP_CLOSED) &&
7937 (dst->state >= SCTP_SHUTDOWN_SENT || dst->state == SCTP_CLOSED) &&
7938 pd->sctp_flags & PFDESC_SCTP_INIT) {
7939 pf_set_protostate(*state, PF_PEER_BOTH, SCTP_CLOSED);
7940 pf_remove_state(*state);
7941 *state = NULL;
7942 return (PF_DROP);
7943 }
7944
7945 if (pf_sctp_track(*state, pd, reason) != PF_PASS)
7946 return (PF_DROP);
7947
7948 /* Track state. */
7949 if (pd->sctp_flags & PFDESC_SCTP_INIT) {
7950 if (src->state < SCTP_COOKIE_WAIT) {
7951 pf_set_protostate(*state, psrc, SCTP_COOKIE_WAIT);
7952 (*state)->timeout = PFTM_SCTP_OPENING;
7953 }
7954 }
7955 if (pd->sctp_flags & PFDESC_SCTP_INIT_ACK) {
7956 MPASS(dst->scrub != NULL);
7957 if (dst->scrub->pfss_v_tag == 0)
7958 dst->scrub->pfss_v_tag = pd->sctp_initiate_tag;
7959 }
7960
7961 /*
7962 * Bind to the correct interface if we're if-bound. For multihomed
7963 * extra associations we don't know which interface that will be until
7964 * here, so we've inserted the state on V_pf_all. Fix that now.
7965 */
7966 if ((*state)->kif == V_pfi_all &&
7967 (*state)->rule->rule_flag & PFRULE_IFBOUND)
7968 (*state)->kif = pd->kif;
7969
7970 if (pd->sctp_flags & (PFDESC_SCTP_COOKIE | PFDESC_SCTP_HEARTBEAT_ACK)) {
7971 if (src->state < SCTP_ESTABLISHED) {
7972 pf_set_protostate(*state, psrc, SCTP_ESTABLISHED);
7973 (*state)->timeout = PFTM_SCTP_ESTABLISHED;
7974 }
7975 }
7976 if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN |
7977 PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
7978 if (src->state < SCTP_SHUTDOWN_PENDING) {
7979 pf_set_protostate(*state, psrc, SCTP_SHUTDOWN_PENDING);
7980 (*state)->timeout = PFTM_SCTP_CLOSING;
7981 }
7982 }
7983 if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN_COMPLETE | PFDESC_SCTP_ABORT)) {
7984 pf_set_protostate(*state, psrc, SCTP_CLOSED);
7985 (*state)->timeout = PFTM_SCTP_CLOSED;
7986 }
7987
7988 (*state)->expire = pf_get_uptime();
7989 break;
7990 default:
7991 /* update states */
7992 if (src->state < PFOTHERS_SINGLE)
7993 pf_set_protostate(*state, psrc, PFOTHERS_SINGLE);
7994 if (dst->state == PFOTHERS_SINGLE)
7995 pf_set_protostate(*state, pdst, PFOTHERS_MULTIPLE);
7996
7997 /* update expire time */
7998 (*state)->expire = pf_get_uptime();
7999 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
8000 (*state)->timeout = PFTM_OTHER_MULTIPLE;
8001 else
8002 (*state)->timeout = PFTM_OTHER_SINGLE;
8003 break;
8004 }
8005
8006 /* translate source/destination address, if necessary */
8007 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
8008 struct pf_state_key *nk;
8009 int afto, sidx, didx;
8010
8011 if (PF_REVERSED_KEY(*state, pd->af))
8012 nk = (*state)->key[pd->sidx];
8013 else
8014 nk = (*state)->key[pd->didx];
8015
8016 afto = pd->af != nk->af;
8017
8018 if (afto && (*state)->direction == PF_IN) {
8019 sidx = pd->didx;
8020 didx = pd->sidx;
8021 } else {
8022 sidx = pd->sidx;
8023 didx = pd->didx;
8024 }
8025
8026 if (afto) {
8027 pf_addrcpy(&pd->nsaddr, &nk->addr[sidx], nk->af);
8028 pf_addrcpy(&pd->ndaddr, &nk->addr[didx], nk->af);
8029 pd->naf = nk->af;
8030 action = PF_AFRT;
8031 }
8032
8033 if (afto || PF_ANEQ(pd->src, &nk->addr[sidx], pd->af) ||
8034 nk->port[sidx] != pd->osport)
8035 pf_change_ap(pd, pd->src, pd->sport,
8036 &nk->addr[sidx], nk->port[sidx]);
8037
8038 if (afto || PF_ANEQ(pd->dst, &nk->addr[didx], pd->af) ||
8039 nk->port[didx] != pd->odport)
8040 pf_change_ap(pd, pd->dst, pd->dport,
8041 &nk->addr[didx], nk->port[didx]);
8042
8043 copyback = 1;
8044 }
8045
8046 if (copyback && pd->hdrlen > 0)
8047 m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
8048
8049 return (action);
8050 }
8051
8052 static int
pf_sctp_track(struct pf_kstate * state,struct pf_pdesc * pd,u_short * reason)8053 pf_sctp_track(struct pf_kstate *state, struct pf_pdesc *pd,
8054 u_short *reason)
8055 {
8056 struct pf_state_peer *src;
8057 if (pd->dir == state->direction) {
8058 if (PF_REVERSED_KEY(state, pd->af))
8059 src = &state->dst;
8060 else
8061 src = &state->src;
8062 } else {
8063 if (PF_REVERSED_KEY(state, pd->af))
8064 src = &state->src;
8065 else
8066 src = &state->dst;
8067 }
8068
8069 if (src->scrub != NULL) {
8070 /*
8071 * Allow tags to be updated, in case of retransmission of
8072 * INIT/INIT_ACK chunks.
8073 **/
8074 if (src->state <= SCTP_COOKIE_WAIT)
8075 src->scrub->pfss_v_tag = pd->hdr.sctp.v_tag;
8076 else if (src->scrub->pfss_v_tag != pd->hdr.sctp.v_tag)
8077 return (PF_DROP);
8078 }
8079
8080 return (PF_PASS);
8081 }
8082
8083 static void
pf_sctp_multihome_detach_addr(const struct pf_kstate * s)8084 pf_sctp_multihome_detach_addr(const struct pf_kstate *s)
8085 {
8086 struct pf_sctp_endpoint key;
8087 struct pf_sctp_endpoint *ep;
8088 struct pf_state_key *sks = s->key[PF_SK_STACK];
8089 struct pf_sctp_source *i, *tmp;
8090
8091 if (sks == NULL || sks->proto != IPPROTO_SCTP || s->dst.scrub == NULL)
8092 return;
8093
8094 PF_SCTP_ENDPOINTS_LOCK();
8095
8096 key.v_tag = s->dst.scrub->pfss_v_tag;
8097 ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
8098 if (ep != NULL) {
8099 TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
8100 if (pf_addr_cmp(&i->addr,
8101 &s->key[PF_SK_WIRE]->addr[s->direction == PF_OUT],
8102 s->key[PF_SK_WIRE]->af) == 0) {
8103 SDT_PROBE3(pf, sctp, multihome, remove,
8104 key.v_tag, s, i);
8105 TAILQ_REMOVE(&ep->sources, i, entry);
8106 free(i, M_PFTEMP);
8107 break;
8108 }
8109 }
8110
8111 if (TAILQ_EMPTY(&ep->sources)) {
8112 RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
8113 free(ep, M_PFTEMP);
8114 }
8115 }
8116
8117 /* Other direction. */
8118 key.v_tag = s->src.scrub->pfss_v_tag;
8119 ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
8120 if (ep != NULL) {
8121 TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
8122 if (pf_addr_cmp(&i->addr,
8123 &s->key[PF_SK_WIRE]->addr[s->direction == PF_IN],
8124 s->key[PF_SK_WIRE]->af) == 0) {
8125 SDT_PROBE3(pf, sctp, multihome, remove,
8126 key.v_tag, s, i);
8127 TAILQ_REMOVE(&ep->sources, i, entry);
8128 free(i, M_PFTEMP);
8129 break;
8130 }
8131 }
8132
8133 if (TAILQ_EMPTY(&ep->sources)) {
8134 RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
8135 free(ep, M_PFTEMP);
8136 }
8137 }
8138
8139 PF_SCTP_ENDPOINTS_UNLOCK();
8140 }
8141
8142 static void
pf_sctp_multihome_add_addr(struct pf_pdesc * pd,struct pf_addr * a,uint32_t v_tag)8143 pf_sctp_multihome_add_addr(struct pf_pdesc *pd, struct pf_addr *a, uint32_t v_tag)
8144 {
8145 struct pf_sctp_endpoint key = {
8146 .v_tag = v_tag,
8147 };
8148 struct pf_sctp_source *i;
8149 struct pf_sctp_endpoint *ep;
8150 int count;
8151
8152 PF_SCTP_ENDPOINTS_LOCK();
8153
8154 ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
8155 if (ep == NULL) {
8156 ep = malloc(sizeof(struct pf_sctp_endpoint),
8157 M_PFTEMP, M_NOWAIT);
8158 if (ep == NULL) {
8159 PF_SCTP_ENDPOINTS_UNLOCK();
8160 return;
8161 }
8162
8163 ep->v_tag = v_tag;
8164 TAILQ_INIT(&ep->sources);
8165 RB_INSERT(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
8166 }
8167
8168 /* Avoid inserting duplicates. */
8169 count = 0;
8170 TAILQ_FOREACH(i, &ep->sources, entry) {
8171 count++;
8172 if (pf_addr_cmp(&i->addr, a, pd->af) == 0) {
8173 PF_SCTP_ENDPOINTS_UNLOCK();
8174 return;
8175 }
8176 }
8177
8178 /* Limit the number of addresses per endpoint. */
8179 if (count >= PF_SCTP_MAX_ENDPOINTS) {
8180 PF_SCTP_ENDPOINTS_UNLOCK();
8181 return;
8182 }
8183
8184 i = malloc(sizeof(*i), M_PFTEMP, M_NOWAIT);
8185 if (i == NULL) {
8186 PF_SCTP_ENDPOINTS_UNLOCK();
8187 return;
8188 }
8189
8190 i->af = pd->af;
8191 memcpy(&i->addr, a, sizeof(*a));
8192 TAILQ_INSERT_TAIL(&ep->sources, i, entry);
8193 SDT_PROBE2(pf, sctp, multihome, add, v_tag, i);
8194
8195 PF_SCTP_ENDPOINTS_UNLOCK();
8196 }
8197
8198 static void
pf_sctp_multihome_delayed(struct pf_pdesc * pd,struct pfi_kkif * kif,struct pf_kstate * s,int action)8199 pf_sctp_multihome_delayed(struct pf_pdesc *pd, struct pfi_kkif *kif,
8200 struct pf_kstate *s, int action)
8201 {
8202 struct pf_krule_slist match_rules;
8203 struct pf_sctp_multihome_job *j, *tmp;
8204 struct pf_sctp_source *i;
8205 int ret;
8206 struct pf_kstate *sm = NULL;
8207 struct pf_krule *ra = NULL;
8208 struct pf_krule *r = &V_pf_default_rule;
8209 struct pf_kruleset *rs = NULL;
8210 u_short reason;
8211 bool do_extra = true;
8212
8213 PF_RULES_RLOCK_TRACKER;
8214
8215 again:
8216 TAILQ_FOREACH_SAFE(j, &pd->sctp_multihome_jobs, next, tmp) {
8217 if (s == NULL || action != PF_PASS)
8218 goto free;
8219
8220 /* Confirm we don't recurse here. */
8221 MPASS(! (pd->sctp_flags & PFDESC_SCTP_ADD_IP));
8222
8223 switch (j->op) {
8224 case SCTP_ADD_IP_ADDRESS: {
8225 uint32_t v_tag = pd->sctp_initiate_tag;
8226
8227 if (v_tag == 0) {
8228 if (s->direction == pd->dir)
8229 v_tag = s->src.scrub->pfss_v_tag;
8230 else
8231 v_tag = s->dst.scrub->pfss_v_tag;
8232 }
8233
8234 /*
8235 * Avoid duplicating states. We'll already have
8236 * created a state based on the source address of
8237 * the packet, but SCTP endpoints may also list this
8238 * address again in the INIT(_ACK) parameters.
8239 */
8240 if (pf_addr_cmp(&j->src, pd->src, pd->af) == 0) {
8241 break;
8242 }
8243
8244 j->pd.sctp_flags |= PFDESC_SCTP_ADD_IP;
8245 PF_RULES_RLOCK();
8246 sm = NULL;
8247 if (s->rule->rule_flag & PFRULE_ALLOW_RELATED) {
8248 j->pd.related_rule = s->rule;
8249 }
8250 SLIST_INIT(&match_rules);
8251 ret = pf_test_rule(&r, &sm,
8252 &j->pd, &ra, &rs, &reason, NULL, &match_rules);
8253 /*
8254 * Nothing to do about match rules, the processed
8255 * packet has already increased the counters.
8256 */
8257 pf_free_match_rules(&match_rules);
8258 PF_RULES_RUNLOCK();
8259 SDT_PROBE4(pf, sctp, multihome, test, kif, r, j->pd.m, ret);
8260 if (ret != PF_DROP && sm != NULL) {
8261 /* Inherit v_tag values. */
8262 if (sm->direction == s->direction) {
8263 sm->src.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
8264 sm->dst.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
8265 } else {
8266 sm->src.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
8267 sm->dst.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
8268 }
8269 PF_STATE_UNLOCK(sm);
8270 } else {
8271 /* If we try duplicate inserts? */
8272 break;
8273 }
8274
8275 /* Only add the address if we've actually allowed the state. */
8276 pf_sctp_multihome_add_addr(pd, &j->src, v_tag);
8277
8278 if (! do_extra) {
8279 break;
8280 }
8281 /*
8282 * We need to do this for each of our source addresses.
8283 * Find those based on the verification tag.
8284 */
8285 struct pf_sctp_endpoint key = {
8286 .v_tag = pd->hdr.sctp.v_tag,
8287 };
8288 struct pf_sctp_endpoint *ep;
8289
8290 PF_SCTP_ENDPOINTS_LOCK();
8291 ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
8292 if (ep == NULL) {
8293 PF_SCTP_ENDPOINTS_UNLOCK();
8294 break;
8295 }
8296 MPASS(ep != NULL);
8297
8298 TAILQ_FOREACH(i, &ep->sources, entry) {
8299 struct pf_sctp_multihome_job *nj;
8300
8301 /* SCTP can intermingle IPv4 and IPv6. */
8302 if (i->af != pd->af)
8303 continue;
8304
8305 nj = malloc(sizeof(*nj), M_PFTEMP, M_NOWAIT | M_ZERO);
8306 if (! nj) {
8307 continue;
8308 }
8309 memcpy(&nj->pd, &j->pd, sizeof(j->pd));
8310 memcpy(&nj->src, &j->src, sizeof(nj->src));
8311 nj->pd.src = &nj->src;
8312 // New destination address!
8313 memcpy(&nj->dst, &i->addr, sizeof(nj->dst));
8314 nj->pd.dst = &nj->dst;
8315 nj->pd.m = j->pd.m;
8316 nj->op = j->op;
8317
8318 MPASS(nj->pd.pcksum);
8319 TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, nj, next);
8320 }
8321 PF_SCTP_ENDPOINTS_UNLOCK();
8322
8323 break;
8324 }
8325 case SCTP_DEL_IP_ADDRESS: {
8326 struct pf_state_key_cmp key;
8327 uint8_t psrc;
8328 int action;
8329
8330 bzero(&key, sizeof(key));
8331 key.af = j->pd.af;
8332 key.proto = IPPROTO_SCTP;
8333 if (j->pd.dir == PF_IN) { /* wire side, straight */
8334 pf_addrcpy(&key.addr[0], j->pd.src, key.af);
8335 pf_addrcpy(&key.addr[1], j->pd.dst, key.af);
8336 key.port[0] = j->pd.hdr.sctp.src_port;
8337 key.port[1] = j->pd.hdr.sctp.dest_port;
8338 } else { /* stack side, reverse */
8339 pf_addrcpy(&key.addr[1], j->pd.src, key.af);
8340 pf_addrcpy(&key.addr[0], j->pd.dst, key.af);
8341 key.port[1] = j->pd.hdr.sctp.src_port;
8342 key.port[0] = j->pd.hdr.sctp.dest_port;
8343 }
8344
8345 action = pf_find_state(&j->pd, &key, &sm);
8346 if (action == PF_MATCH) {
8347 PF_STATE_LOCK_ASSERT(sm);
8348 if (j->pd.dir == sm->direction) {
8349 psrc = PF_PEER_SRC;
8350 } else {
8351 psrc = PF_PEER_DST;
8352 }
8353 pf_set_protostate(sm, psrc, SCTP_SHUTDOWN_PENDING);
8354 sm->timeout = PFTM_SCTP_CLOSING;
8355 PF_STATE_UNLOCK(sm);
8356 }
8357 break;
8358 default:
8359 panic("Unknown op %#x", j->op);
8360 }
8361 }
8362
8363 free:
8364 TAILQ_REMOVE(&pd->sctp_multihome_jobs, j, next);
8365 free(j, M_PFTEMP);
8366 }
8367
8368 /* We may have inserted extra work while processing the list. */
8369 if (! TAILQ_EMPTY(&pd->sctp_multihome_jobs)) {
8370 do_extra = false;
8371 goto again;
8372 }
8373 }
8374
8375 static int
pf_multihome_scan(int start,int len,struct pf_pdesc * pd,int op,bool asconf)8376 pf_multihome_scan(int start, int len, struct pf_pdesc *pd, int op, bool asconf)
8377 {
8378 int off = 0;
8379 struct pf_sctp_multihome_job *job;
8380
8381 SDT_PROBE4(pf, sctp, multihome_scan, entry, start, len, pd, op);
8382
8383 while (off < len) {
8384 struct sctp_paramhdr h;
8385
8386 if (!pf_pull_hdr(pd->m, start + off, &h, sizeof(h), NULL,
8387 pd->af))
8388 return (PF_DROP);
8389
8390 /* Parameters are at least 4 bytes. */
8391 if (ntohs(h.param_length) < 4)
8392 return (PF_DROP);
8393
8394 SDT_PROBE2(pf, sctp, multihome_scan, param, ntohs(h.param_type),
8395 ntohs(h.param_length));
8396
8397 switch (ntohs(h.param_type)) {
8398 case SCTP_IPV4_ADDRESS: {
8399 struct in_addr t;
8400
8401 if (ntohs(h.param_length) !=
8402 (sizeof(struct sctp_paramhdr) + sizeof(t)))
8403 return (PF_DROP);
8404
8405 if (!pf_pull_hdr(pd->m, start + off + sizeof(h), &t, sizeof(t),
8406 NULL, pd->af))
8407 return (PF_DROP);
8408
8409 if (in_nullhost(t))
8410 t.s_addr = pd->src->v4.s_addr;
8411
8412 /*
8413 * We hold the state lock (idhash) here, which means
8414 * that we can't acquire the keyhash, or we'll get a
8415 * LOR (and potentially double-lock things too). We also
8416 * can't release the state lock here, so instead we'll
8417 * enqueue this for async handling.
8418 * There's a relatively small race here, in that a
8419 * packet using the new addresses could arrive already,
8420 * but that's just though luck for it.
8421 */
8422 job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
8423 if (! job)
8424 return (PF_DROP);
8425
8426 SDT_PROBE2(pf, sctp, multihome_scan, ipv4, &t, op);
8427
8428 memcpy(&job->pd, pd, sizeof(*pd));
8429
8430 // New source address!
8431 memcpy(&job->src, &t, sizeof(t));
8432 job->pd.src = &job->src;
8433 memcpy(&job->dst, pd->dst, sizeof(job->dst));
8434 job->pd.dst = &job->dst;
8435 job->pd.m = pd->m;
8436 job->op = op;
8437
8438 MPASS(job->pd.pcksum);
8439 TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
8440 break;
8441 }
8442 #ifdef INET6
8443 case SCTP_IPV6_ADDRESS: {
8444 struct in6_addr t;
8445
8446 if (ntohs(h.param_length) !=
8447 (sizeof(struct sctp_paramhdr) + sizeof(t)))
8448 return (PF_DROP);
8449
8450 if (!pf_pull_hdr(pd->m, start + off + sizeof(h), &t, sizeof(t),
8451 NULL, pd->af))
8452 return (PF_DROP);
8453 if (memcmp(&t, &pd->src->v6, sizeof(t)) == 0)
8454 break;
8455 if (memcmp(&t, &in6addr_any, sizeof(t)) == 0)
8456 memcpy(&t, &pd->src->v6, sizeof(t));
8457
8458 job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
8459 if (! job)
8460 return (PF_DROP);
8461
8462 SDT_PROBE2(pf, sctp, multihome_scan, ipv6, &t, op);
8463
8464 memcpy(&job->pd, pd, sizeof(*pd));
8465 memcpy(&job->src, &t, sizeof(t));
8466 job->pd.src = &job->src;
8467 memcpy(&job->dst, pd->dst, sizeof(job->dst));
8468 job->pd.dst = &job->dst;
8469 job->pd.m = pd->m;
8470 job->op = op;
8471
8472 MPASS(job->pd.pcksum);
8473 TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
8474 break;
8475 }
8476 #endif /* INET6 */
8477 case SCTP_ADD_IP_ADDRESS: {
8478 int ret;
8479 struct sctp_asconf_paramhdr ah;
8480
8481 if (asconf)
8482 return (PF_DROP);
8483
8484 if (!pf_pull_hdr(pd->m, start + off, &ah, sizeof(ah),
8485 NULL, pd->af))
8486 return (PF_DROP);
8487
8488 if (ntohs(ah.ph.param_length) < sizeof(ah))
8489 return (PF_DROP);
8490
8491 ret = pf_multihome_scan(start + off + sizeof(ah),
8492 ntohs(ah.ph.param_length) - sizeof(ah), pd,
8493 SCTP_ADD_IP_ADDRESS, true);
8494 if (ret != PF_PASS)
8495 return (ret);
8496 break;
8497 }
8498 case SCTP_DEL_IP_ADDRESS: {
8499 int ret;
8500 struct sctp_asconf_paramhdr ah;
8501
8502 if (asconf)
8503 return (PF_DROP);
8504
8505 if (!pf_pull_hdr(pd->m, start + off, &ah, sizeof(ah),
8506 NULL, pd->af))
8507 return (PF_DROP);
8508
8509 if (ntohs(ah.ph.param_length) < sizeof(ah))
8510 return (PF_DROP);
8511
8512 ret = pf_multihome_scan(start + off + sizeof(ah),
8513 ntohs(ah.ph.param_length) - sizeof(ah), pd,
8514 SCTP_DEL_IP_ADDRESS, true);
8515 if (ret != PF_PASS)
8516 return (ret);
8517 break;
8518 }
8519 default:
8520 break;
8521 }
8522
8523 off += roundup(ntohs(h.param_length), 4);
8524 }
8525
8526 return (PF_PASS);
8527 }
8528
8529 int
pf_multihome_scan_init(int start,int len,struct pf_pdesc * pd)8530 pf_multihome_scan_init(int start, int len, struct pf_pdesc *pd)
8531 {
8532 start += sizeof(struct sctp_init_chunk);
8533 len -= sizeof(struct sctp_init_chunk);
8534
8535 return (pf_multihome_scan(start, len, pd, SCTP_ADD_IP_ADDRESS, false));
8536 }
8537
8538 int
pf_multihome_scan_asconf(int start,int len,struct pf_pdesc * pd)8539 pf_multihome_scan_asconf(int start, int len, struct pf_pdesc *pd)
8540 {
8541 start += sizeof(struct sctp_asconf_chunk);
8542 len -= sizeof(struct sctp_asconf_chunk);
8543
8544 return (pf_multihome_scan(start, len, pd, SCTP_ADD_IP_ADDRESS, false));
8545 }
8546
8547 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)8548 pf_icmp_state_lookup(struct pf_state_key_cmp *key, struct pf_pdesc *pd,
8549 struct pf_kstate **state, u_int16_t icmpid, u_int16_t type, int icmp_dir,
8550 int *iidx, int multi, int inner)
8551 {
8552 int action, direction = pd->dir;
8553
8554 key->af = pd->af;
8555 key->proto = pd->proto;
8556 if (icmp_dir == PF_IN) {
8557 *iidx = pd->sidx;
8558 key->port[pd->sidx] = icmpid;
8559 key->port[pd->didx] = type;
8560 } else {
8561 *iidx = pd->didx;
8562 key->port[pd->sidx] = type;
8563 key->port[pd->didx] = icmpid;
8564 }
8565 if (pf_state_key_addr_setup(pd, key, multi))
8566 return (PF_DROP);
8567
8568 action = pf_find_state(pd, key, state);
8569 if (action != PF_MATCH && action != PF_PASS)
8570 return (action);
8571
8572 if ((*state)->state_flags & PFSTATE_SLOPPY)
8573 return (-1);
8574
8575 /* Is this ICMP message flowing in right direction? */
8576 if ((*state)->key[PF_SK_WIRE]->af != (*state)->key[PF_SK_STACK]->af)
8577 direction = (pd->af == (*state)->key[PF_SK_WIRE]->af) ?
8578 PF_IN : PF_OUT;
8579 else
8580 direction = (*state)->direction;
8581 if ((*state)->rule->type &&
8582 (((!inner && direction == pd->dir) ||
8583 (inner && direction != pd->dir)) ?
8584 PF_IN : PF_OUT) != icmp_dir) {
8585 if (V_pf_status.debug >= PF_DEBUG_MISC) {
8586 printf("pf: icmp type %d in wrong direction (%d): ",
8587 ntohs(type), icmp_dir);
8588 pf_print_state(*state);
8589 printf("\n");
8590 }
8591 PF_STATE_UNLOCK(*state);
8592 *state = NULL;
8593 return (PF_DROP);
8594 }
8595 return (-1);
8596 }
8597
8598 static int
pf_test_state_icmp(struct pf_kstate ** state,struct pf_pdesc * pd,u_short * reason)8599 pf_test_state_icmp(struct pf_kstate **state, struct pf_pdesc *pd,
8600 u_short *reason)
8601 {
8602 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
8603 u_int16_t *icmpsum, virtual_id, virtual_type;
8604 u_int8_t icmptype, icmpcode;
8605 int icmp_dir, iidx, ret;
8606 struct pf_state_key_cmp key;
8607 #ifdef INET
8608 u_int16_t icmpid;
8609 #endif /* INET*/
8610
8611 MPASS(*state == NULL);
8612
8613 bzero(&key, sizeof(key));
8614 switch (pd->proto) {
8615 #ifdef INET
8616 case IPPROTO_ICMP:
8617 icmptype = pd->hdr.icmp.icmp_type;
8618 icmpcode = pd->hdr.icmp.icmp_code;
8619 icmpid = pd->hdr.icmp.icmp_id;
8620 icmpsum = &pd->hdr.icmp.icmp_cksum;
8621 break;
8622 #endif /* INET */
8623 #ifdef INET6
8624 case IPPROTO_ICMPV6:
8625 icmptype = pd->hdr.icmp6.icmp6_type;
8626 icmpcode = pd->hdr.icmp6.icmp6_code;
8627 #ifdef INET
8628 icmpid = pd->hdr.icmp6.icmp6_id;
8629 #endif /* INET */
8630 icmpsum = &pd->hdr.icmp6.icmp6_cksum;
8631 break;
8632 #endif /* INET6 */
8633 default:
8634 panic("unhandled proto %d", pd->proto);
8635 }
8636
8637 if (pf_icmp_mapping(pd, icmptype, &icmp_dir, &virtual_id,
8638 &virtual_type) == 0) {
8639 /*
8640 * ICMP query/reply message not related to a TCP/UDP/SCTP
8641 * packet. Search for an ICMP state.
8642 */
8643 ret = pf_icmp_state_lookup(&key, pd, state, virtual_id,
8644 virtual_type, icmp_dir, &iidx, 0, 0);
8645 /* IPv6? try matching a multicast address */
8646 if (ret == PF_DROP && pd->af == AF_INET6 && icmp_dir == PF_OUT) {
8647 MPASS(*state == NULL);
8648 ret = pf_icmp_state_lookup(&key, pd, state,
8649 virtual_id, virtual_type,
8650 icmp_dir, &iidx, 1, 0);
8651 }
8652 if (ret >= 0) {
8653 MPASS(*state == NULL);
8654 return (ret);
8655 }
8656
8657 (*state)->expire = pf_get_uptime();
8658 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
8659
8660 /* translate source/destination address, if necessary */
8661 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
8662 struct pf_state_key *nk;
8663 int afto, sidx, didx;
8664
8665 if (PF_REVERSED_KEY(*state, pd->af))
8666 nk = (*state)->key[pd->sidx];
8667 else
8668 nk = (*state)->key[pd->didx];
8669
8670 afto = pd->af != nk->af;
8671
8672 if (afto && (*state)->direction == PF_IN) {
8673 sidx = pd->didx;
8674 didx = pd->sidx;
8675 iidx = !iidx;
8676 } else {
8677 sidx = pd->sidx;
8678 didx = pd->didx;
8679 }
8680
8681 switch (pd->af) {
8682 #ifdef INET
8683 case AF_INET:
8684 #ifdef INET6
8685 if (afto) {
8686 if (pf_translate_icmp_af(AF_INET6,
8687 &pd->hdr.icmp))
8688 return (PF_DROP);
8689 pd->proto = IPPROTO_ICMPV6;
8690 }
8691 #endif /* INET6 */
8692 if (!afto &&
8693 PF_ANEQ(pd->src, &nk->addr[sidx], AF_INET))
8694 pf_change_a(&saddr->v4.s_addr,
8695 pd->ip_sum,
8696 nk->addr[sidx].v4.s_addr,
8697 0);
8698
8699 if (!afto && PF_ANEQ(pd->dst,
8700 &nk->addr[didx], AF_INET))
8701 pf_change_a(&daddr->v4.s_addr,
8702 pd->ip_sum,
8703 nk->addr[didx].v4.s_addr, 0);
8704
8705 if (nk->port[iidx] !=
8706 pd->hdr.icmp.icmp_id) {
8707 pd->hdr.icmp.icmp_cksum =
8708 pf_cksum_fixup(
8709 pd->hdr.icmp.icmp_cksum, icmpid,
8710 nk->port[iidx], 0);
8711 pd->hdr.icmp.icmp_id =
8712 nk->port[iidx];
8713 }
8714
8715 m_copyback(pd->m, pd->off, ICMP_MINLEN,
8716 (caddr_t )&pd->hdr.icmp);
8717 break;
8718 #endif /* INET */
8719 #ifdef INET6
8720 case AF_INET6:
8721 #ifdef INET
8722 if (afto) {
8723 if (pf_translate_icmp_af(AF_INET,
8724 &pd->hdr.icmp6))
8725 return (PF_DROP);
8726 pd->proto = IPPROTO_ICMP;
8727 }
8728 #endif /* INET */
8729 if (!afto &&
8730 PF_ANEQ(pd->src, &nk->addr[sidx], AF_INET6))
8731 pf_change_a6(saddr,
8732 &pd->hdr.icmp6.icmp6_cksum,
8733 &nk->addr[sidx], 0);
8734
8735 if (!afto && PF_ANEQ(pd->dst,
8736 &nk->addr[didx], AF_INET6))
8737 pf_change_a6(daddr,
8738 &pd->hdr.icmp6.icmp6_cksum,
8739 &nk->addr[didx], 0);
8740
8741 if (nk->port[iidx] != pd->hdr.icmp6.icmp6_id)
8742 pd->hdr.icmp6.icmp6_id =
8743 nk->port[iidx];
8744
8745 m_copyback(pd->m, pd->off, sizeof(struct icmp6_hdr),
8746 (caddr_t )&pd->hdr.icmp6);
8747 break;
8748 #endif /* INET6 */
8749 }
8750 if (afto) {
8751 pf_addrcpy(&pd->nsaddr, &nk->addr[sidx],
8752 nk->af);
8753 pf_addrcpy(&pd->ndaddr, &nk->addr[didx],
8754 nk->af);
8755 pd->naf = nk->af;
8756 return (PF_AFRT);
8757 }
8758 }
8759 return (PF_PASS);
8760
8761 } else {
8762 /*
8763 * ICMP error message in response to a TCP/UDP packet.
8764 * Extract the inner TCP/UDP header and search for that state.
8765 */
8766
8767 struct pf_pdesc pd2;
8768 bzero(&pd2, sizeof pd2);
8769 #ifdef INET
8770 struct ip h2;
8771 #endif /* INET */
8772 #ifdef INET6
8773 struct ip6_hdr h2_6;
8774 #endif /* INET6 */
8775 int ipoff2 = 0;
8776
8777 pd2.af = pd->af;
8778 pd2.dir = pd->dir;
8779 /* Payload packet is from the opposite direction. */
8780 pd2.sidx = (pd->dir == PF_IN) ? 1 : 0;
8781 pd2.didx = (pd->dir == PF_IN) ? 0 : 1;
8782 pd2.m = pd->m;
8783 pd2.pf_mtag = pd->pf_mtag;
8784 pd2.kif = pd->kif;
8785 switch (pd->af) {
8786 #ifdef INET
8787 case AF_INET:
8788 /* offset of h2 in mbuf chain */
8789 ipoff2 = pd->off + ICMP_MINLEN;
8790
8791 if (!pf_pull_hdr(pd->m, ipoff2, &h2, sizeof(h2),
8792 reason, pd2.af)) {
8793 DPFPRINTF(PF_DEBUG_MISC,
8794 "pf: ICMP error message too short "
8795 "(ip)");
8796 return (PF_DROP);
8797 }
8798 /*
8799 * ICMP error messages don't refer to non-first
8800 * fragments
8801 */
8802 if (h2.ip_off & htons(IP_OFFMASK)) {
8803 REASON_SET(reason, PFRES_FRAG);
8804 return (PF_DROP);
8805 }
8806
8807 /* offset of protocol header that follows h2 */
8808 pd2.off = ipoff2;
8809 if (pf_walk_header(&pd2, &h2, reason) != PF_PASS)
8810 return (PF_DROP);
8811
8812 pd2.tot_len = ntohs(h2.ip_len);
8813 pd2.ttl = h2.ip_ttl;
8814 pd2.src = (struct pf_addr *)&h2.ip_src;
8815 pd2.dst = (struct pf_addr *)&h2.ip_dst;
8816 pd2.ip_sum = &h2.ip_sum;
8817 break;
8818 #endif /* INET */
8819 #ifdef INET6
8820 case AF_INET6:
8821 ipoff2 = pd->off + sizeof(struct icmp6_hdr);
8822
8823 if (!pf_pull_hdr(pd->m, ipoff2, &h2_6, sizeof(h2_6),
8824 reason, pd2.af)) {
8825 DPFPRINTF(PF_DEBUG_MISC,
8826 "pf: ICMP error message too short "
8827 "(ip6)");
8828 return (PF_DROP);
8829 }
8830 pd2.off = ipoff2;
8831 if (pf_walk_header6(&pd2, &h2_6, reason) != PF_PASS)
8832 return (PF_DROP);
8833
8834 pd2.tot_len = ntohs(h2_6.ip6_plen) +
8835 sizeof(struct ip6_hdr);
8836 pd2.ttl = h2_6.ip6_hlim;
8837 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
8838 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
8839 pd2.ip_sum = NULL;
8840 break;
8841 #endif /* INET6 */
8842 default:
8843 unhandled_af(pd->af);
8844 }
8845
8846 if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
8847 if (V_pf_status.debug >= PF_DEBUG_MISC) {
8848 printf("pf: BAD ICMP %d:%d outer dst: ",
8849 icmptype, icmpcode);
8850 pf_print_host(pd->src, 0, pd->af);
8851 printf(" -> ");
8852 pf_print_host(pd->dst, 0, pd->af);
8853 printf(" inner src: ");
8854 pf_print_host(pd2.src, 0, pd2.af);
8855 printf(" -> ");
8856 pf_print_host(pd2.dst, 0, pd2.af);
8857 printf("\n");
8858 }
8859 REASON_SET(reason, PFRES_BADSTATE);
8860 return (PF_DROP);
8861 }
8862
8863 switch (pd2.proto) {
8864 case IPPROTO_TCP: {
8865 struct tcphdr *th = &pd2.hdr.tcp;
8866 u_int32_t seq;
8867 struct pf_state_peer *src, *dst;
8868 u_int8_t dws;
8869 int copyback = 0;
8870 int action;
8871
8872 /*
8873 * Only the first 8 bytes of the TCP header can be
8874 * expected. Don't access any TCP header fields after
8875 * th_seq, an ackskew test is not possible.
8876 */
8877 if (!pf_pull_hdr(pd->m, pd2.off, th, 8, reason,
8878 pd2.af)) {
8879 DPFPRINTF(PF_DEBUG_MISC,
8880 "pf: ICMP error message too short "
8881 "(tcp)");
8882 return (PF_DROP);
8883 }
8884 pd2.pcksum = &pd2.hdr.tcp.th_sum;
8885
8886 key.af = pd2.af;
8887 key.proto = IPPROTO_TCP;
8888 pf_addrcpy(&key.addr[pd2.sidx], pd2.src, key.af);
8889 pf_addrcpy(&key.addr[pd2.didx], pd2.dst, key.af);
8890 key.port[pd2.sidx] = th->th_sport;
8891 key.port[pd2.didx] = th->th_dport;
8892
8893 action = pf_find_state(&pd2, &key, state);
8894 if (action != PF_MATCH && action != PF_PASS)
8895 return (action);
8896
8897 if (pd->dir == (*state)->direction) {
8898 if (PF_REVERSED_KEY(*state, pd->af)) {
8899 src = &(*state)->src;
8900 dst = &(*state)->dst;
8901 } else {
8902 src = &(*state)->dst;
8903 dst = &(*state)->src;
8904 }
8905 } else {
8906 if (PF_REVERSED_KEY(*state, pd->af)) {
8907 src = &(*state)->dst;
8908 dst = &(*state)->src;
8909 } else {
8910 src = &(*state)->src;
8911 dst = &(*state)->dst;
8912 }
8913 }
8914
8915 if (src->wscale && dst->wscale)
8916 dws = dst->wscale & PF_WSCALE_MASK;
8917 else
8918 dws = 0;
8919
8920 /* Demodulate sequence number */
8921 seq = ntohl(th->th_seq) - src->seqdiff;
8922 if (src->seqdiff) {
8923 pf_change_a(&th->th_seq, icmpsum,
8924 htonl(seq), 0);
8925 copyback = 1;
8926 }
8927
8928 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
8929 (!SEQ_GEQ(src->seqhi, seq) ||
8930 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
8931 if (V_pf_status.debug >= PF_DEBUG_MISC) {
8932 printf("pf: BAD ICMP %d:%d ",
8933 icmptype, icmpcode);
8934 pf_print_host(pd->src, 0, pd->af);
8935 printf(" -> ");
8936 pf_print_host(pd->dst, 0, pd->af);
8937 printf(" state: ");
8938 pf_print_state(*state);
8939 printf(" seq=%u\n", seq);
8940 }
8941 REASON_SET(reason, PFRES_BADSTATE);
8942 return (PF_DROP);
8943 } else {
8944 if (V_pf_status.debug >= PF_DEBUG_MISC) {
8945 printf("pf: OK ICMP %d:%d ",
8946 icmptype, icmpcode);
8947 pf_print_host(pd->src, 0, pd->af);
8948 printf(" -> ");
8949 pf_print_host(pd->dst, 0, pd->af);
8950 printf(" state: ");
8951 pf_print_state(*state);
8952 printf(" seq=%u\n", seq);
8953 }
8954 }
8955
8956 /* translate source/destination address, if necessary */
8957 if ((*state)->key[PF_SK_WIRE] !=
8958 (*state)->key[PF_SK_STACK]) {
8959
8960 struct pf_state_key *nk;
8961
8962 if (PF_REVERSED_KEY(*state, pd->af))
8963 nk = (*state)->key[pd->sidx];
8964 else
8965 nk = (*state)->key[pd->didx];
8966
8967 #if defined(INET) && defined(INET6)
8968 int afto, sidx, didx;
8969
8970 afto = pd->af != nk->af;
8971
8972 if (afto && (*state)->direction == PF_IN) {
8973 sidx = pd2.didx;
8974 didx = pd2.sidx;
8975 } else {
8976 sidx = pd2.sidx;
8977 didx = pd2.didx;
8978 }
8979
8980 if (afto) {
8981 if (pf_translate_icmp_af(nk->af,
8982 &pd->hdr.icmp))
8983 return (PF_DROP);
8984 m_copyback(pd->m, pd->off,
8985 sizeof(struct icmp6_hdr),
8986 (c_caddr_t)&pd->hdr.icmp6);
8987 if (pf_change_icmp_af(pd->m, ipoff2, pd,
8988 &pd2, &nk->addr[sidx],
8989 &nk->addr[didx], pd->af,
8990 nk->af))
8991 return (PF_DROP);
8992 pf_addrcpy(&pd->nsaddr,
8993 &nk->addr[pd2.sidx], nk->af);
8994 pf_addrcpy(&pd->ndaddr,
8995 &nk->addr[pd2.didx], nk->af);
8996 if (nk->af == AF_INET) {
8997 pd->proto = IPPROTO_ICMP;
8998 } else {
8999 pd->proto = IPPROTO_ICMPV6;
9000 /*
9001 * IPv4 becomes IPv6 so we must
9002 * copy IPv4 src addr to least
9003 * 32bits in IPv6 address to
9004 * keep traceroute/icmp
9005 * working.
9006 */
9007 pd->nsaddr.addr32[3] =
9008 pd->src->addr32[0];
9009 }
9010 pd->naf = pd2.naf = nk->af;
9011 pf_change_ap(&pd2, pd2.src, &th->th_sport,
9012 &nk->addr[pd2.sidx], nk->port[sidx]);
9013 pf_change_ap(&pd2, pd2.dst, &th->th_dport,
9014 &nk->addr[pd2.didx], nk->port[didx]);
9015 m_copyback(pd2.m, pd2.off, 8, (c_caddr_t)th);
9016 return (PF_AFRT);
9017 }
9018 #endif /* INET && INET6 */
9019
9020 if (PF_ANEQ(pd2.src,
9021 &nk->addr[pd2.sidx], pd2.af) ||
9022 nk->port[pd2.sidx] != th->th_sport)
9023 pf_change_icmp(pd2.src, &th->th_sport,
9024 daddr, &nk->addr[pd2.sidx],
9025 nk->port[pd2.sidx], NULL,
9026 pd2.ip_sum, icmpsum,
9027 pd->ip_sum, 0, pd2.af);
9028
9029 if (PF_ANEQ(pd2.dst,
9030 &nk->addr[pd2.didx], pd2.af) ||
9031 nk->port[pd2.didx] != th->th_dport)
9032 pf_change_icmp(pd2.dst, &th->th_dport,
9033 saddr, &nk->addr[pd2.didx],
9034 nk->port[pd2.didx], NULL,
9035 pd2.ip_sum, icmpsum,
9036 pd->ip_sum, 0, pd2.af);
9037 copyback = 1;
9038 }
9039
9040 if (copyback) {
9041 switch (pd2.af) {
9042 #ifdef INET
9043 case AF_INET:
9044 m_copyback(pd->m, pd->off, ICMP_MINLEN,
9045 (caddr_t )&pd->hdr.icmp);
9046 m_copyback(pd->m, ipoff2, sizeof(h2),
9047 (caddr_t )&h2);
9048 break;
9049 #endif /* INET */
9050 #ifdef INET6
9051 case AF_INET6:
9052 m_copyback(pd->m, pd->off,
9053 sizeof(struct icmp6_hdr),
9054 (caddr_t )&pd->hdr.icmp6);
9055 m_copyback(pd->m, ipoff2, sizeof(h2_6),
9056 (caddr_t )&h2_6);
9057 break;
9058 #endif /* INET6 */
9059 default:
9060 unhandled_af(pd->af);
9061 }
9062 m_copyback(pd->m, pd2.off, 8, (caddr_t)th);
9063 }
9064
9065 return (PF_PASS);
9066 break;
9067 }
9068 case IPPROTO_UDP: {
9069 struct udphdr *uh = &pd2.hdr.udp;
9070 int action;
9071
9072 if (!pf_pull_hdr(pd->m, pd2.off, uh, sizeof(*uh),
9073 reason, pd2.af)) {
9074 DPFPRINTF(PF_DEBUG_MISC,
9075 "pf: ICMP error message too short "
9076 "(udp)");
9077 return (PF_DROP);
9078 }
9079 pd2.pcksum = &pd2.hdr.udp.uh_sum;
9080
9081 key.af = pd2.af;
9082 key.proto = IPPROTO_UDP;
9083 pf_addrcpy(&key.addr[pd2.sidx], pd2.src, key.af);
9084 pf_addrcpy(&key.addr[pd2.didx], pd2.dst, key.af);
9085 key.port[pd2.sidx] = uh->uh_sport;
9086 key.port[pd2.didx] = uh->uh_dport;
9087
9088 action = pf_find_state(&pd2, &key, state);
9089 if (action != PF_MATCH && action != PF_PASS)
9090 return (action);
9091
9092 /* translate source/destination address, if necessary */
9093 if ((*state)->key[PF_SK_WIRE] !=
9094 (*state)->key[PF_SK_STACK]) {
9095 struct pf_state_key *nk;
9096
9097 if (PF_REVERSED_KEY(*state, pd->af))
9098 nk = (*state)->key[pd->sidx];
9099 else
9100 nk = (*state)->key[pd->didx];
9101
9102 #if defined(INET) && defined(INET6)
9103 int afto, sidx, didx;
9104
9105 afto = pd->af != nk->af;
9106
9107 if (afto && (*state)->direction == PF_IN) {
9108 sidx = pd2.didx;
9109 didx = pd2.sidx;
9110 } else {
9111 sidx = pd2.sidx;
9112 didx = pd2.didx;
9113 }
9114
9115 if (afto) {
9116 if (pf_translate_icmp_af(nk->af,
9117 &pd->hdr.icmp))
9118 return (PF_DROP);
9119 m_copyback(pd->m, pd->off,
9120 sizeof(struct icmp6_hdr),
9121 (c_caddr_t)&pd->hdr.icmp6);
9122 if (pf_change_icmp_af(pd->m, ipoff2, pd,
9123 &pd2, &nk->addr[sidx],
9124 &nk->addr[didx], pd->af,
9125 nk->af))
9126 return (PF_DROP);
9127 pf_addrcpy(&pd->nsaddr,
9128 &nk->addr[pd2.sidx], nk->af);
9129 pf_addrcpy(&pd->ndaddr,
9130 &nk->addr[pd2.didx], nk->af);
9131 if (nk->af == AF_INET) {
9132 pd->proto = IPPROTO_ICMP;
9133 } else {
9134 pd->proto = IPPROTO_ICMPV6;
9135 /*
9136 * IPv4 becomes IPv6 so we must
9137 * copy IPv4 src addr to least
9138 * 32bits in IPv6 address to
9139 * keep traceroute/icmp
9140 * working.
9141 */
9142 pd->nsaddr.addr32[3] =
9143 pd->src->addr32[0];
9144 }
9145 pd->naf = pd2.naf = nk->af;
9146 pf_change_ap(&pd2, pd2.src, &uh->uh_sport,
9147 &nk->addr[pd2.sidx], nk->port[sidx]);
9148 pf_change_ap(&pd2, pd2.dst, &uh->uh_dport,
9149 &nk->addr[pd2.didx], nk->port[didx]);
9150 m_copyback(pd2.m, pd2.off, sizeof(*uh),
9151 (c_caddr_t)uh);
9152 return (PF_AFRT);
9153 }
9154 #endif /* INET && INET6 */
9155
9156 if (PF_ANEQ(pd2.src,
9157 &nk->addr[pd2.sidx], pd2.af) ||
9158 nk->port[pd2.sidx] != uh->uh_sport)
9159 pf_change_icmp(pd2.src, &uh->uh_sport,
9160 daddr, &nk->addr[pd2.sidx],
9161 nk->port[pd2.sidx], &uh->uh_sum,
9162 pd2.ip_sum, icmpsum,
9163 pd->ip_sum, 1, pd2.af);
9164
9165 if (PF_ANEQ(pd2.dst,
9166 &nk->addr[pd2.didx], pd2.af) ||
9167 nk->port[pd2.didx] != uh->uh_dport)
9168 pf_change_icmp(pd2.dst, &uh->uh_dport,
9169 saddr, &nk->addr[pd2.didx],
9170 nk->port[pd2.didx], &uh->uh_sum,
9171 pd2.ip_sum, icmpsum,
9172 pd->ip_sum, 1, pd2.af);
9173
9174 switch (pd2.af) {
9175 #ifdef INET
9176 case AF_INET:
9177 m_copyback(pd->m, pd->off, ICMP_MINLEN,
9178 (caddr_t )&pd->hdr.icmp);
9179 m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
9180 break;
9181 #endif /* INET */
9182 #ifdef INET6
9183 case AF_INET6:
9184 m_copyback(pd->m, pd->off,
9185 sizeof(struct icmp6_hdr),
9186 (caddr_t )&pd->hdr.icmp6);
9187 m_copyback(pd->m, ipoff2, sizeof(h2_6),
9188 (caddr_t )&h2_6);
9189 break;
9190 #endif /* INET6 */
9191 }
9192 m_copyback(pd->m, pd2.off, sizeof(*uh), (caddr_t)uh);
9193 }
9194 return (PF_PASS);
9195 break;
9196 }
9197 #ifdef INET
9198 case IPPROTO_SCTP: {
9199 struct sctphdr *sh = &pd2.hdr.sctp;
9200 struct pf_state_peer *src;
9201 int copyback = 0;
9202 int action;
9203
9204 if (! pf_pull_hdr(pd->m, pd2.off, sh, sizeof(*sh), reason,
9205 pd2.af)) {
9206 DPFPRINTF(PF_DEBUG_MISC,
9207 "pf: ICMP error message too short "
9208 "(sctp)");
9209 return (PF_DROP);
9210 }
9211 pd2.pcksum = &pd2.sctp_dummy_sum;
9212
9213 key.af = pd2.af;
9214 key.proto = IPPROTO_SCTP;
9215 pf_addrcpy(&key.addr[pd2.sidx], pd2.src, key.af);
9216 pf_addrcpy(&key.addr[pd2.didx], pd2.dst, key.af);
9217 key.port[pd2.sidx] = sh->src_port;
9218 key.port[pd2.didx] = sh->dest_port;
9219
9220 action = pf_find_state(&pd2, &key, state);
9221 if (action != PF_MATCH && action != PF_PASS)
9222 return (action);
9223
9224 if (pd->dir == (*state)->direction) {
9225 if (PF_REVERSED_KEY(*state, pd->af))
9226 src = &(*state)->src;
9227 else
9228 src = &(*state)->dst;
9229 } else {
9230 if (PF_REVERSED_KEY(*state, pd->af))
9231 src = &(*state)->dst;
9232 else
9233 src = &(*state)->src;
9234 }
9235
9236 if (src->scrub->pfss_v_tag != sh->v_tag) {
9237 DPFPRINTF(PF_DEBUG_MISC,
9238 "pf: ICMP error message has incorrect "
9239 "SCTP v_tag");
9240 return (PF_DROP);
9241 }
9242
9243 /* translate source/destination address, if necessary */
9244 if ((*state)->key[PF_SK_WIRE] !=
9245 (*state)->key[PF_SK_STACK]) {
9246
9247 struct pf_state_key *nk;
9248
9249 if (PF_REVERSED_KEY(*state, pd->af))
9250 nk = (*state)->key[pd->sidx];
9251 else
9252 nk = (*state)->key[pd->didx];
9253
9254 #if defined(INET) && defined(INET6)
9255 int afto, sidx, didx;
9256
9257 afto = pd->af != nk->af;
9258
9259 if (afto && (*state)->direction == PF_IN) {
9260 sidx = pd2.didx;
9261 didx = pd2.sidx;
9262 } else {
9263 sidx = pd2.sidx;
9264 didx = pd2.didx;
9265 }
9266
9267 if (afto) {
9268 if (pf_translate_icmp_af(nk->af,
9269 &pd->hdr.icmp))
9270 return (PF_DROP);
9271 m_copyback(pd->m, pd->off,
9272 sizeof(struct icmp6_hdr),
9273 (c_caddr_t)&pd->hdr.icmp6);
9274 if (pf_change_icmp_af(pd->m, ipoff2, pd,
9275 &pd2, &nk->addr[sidx],
9276 &nk->addr[didx], pd->af,
9277 nk->af))
9278 return (PF_DROP);
9279 sh->src_port = nk->port[sidx];
9280 sh->dest_port = nk->port[didx];
9281 m_copyback(pd2.m, pd2.off, sizeof(*sh), (c_caddr_t)sh);
9282 pf_addrcpy(&pd->nsaddr,
9283 &nk->addr[pd2.sidx], nk->af);
9284 pf_addrcpy(&pd->ndaddr,
9285 &nk->addr[pd2.didx], nk->af);
9286 if (nk->af == AF_INET) {
9287 pd->proto = IPPROTO_ICMP;
9288 } else {
9289 pd->proto = IPPROTO_ICMPV6;
9290 /*
9291 * IPv4 becomes IPv6 so we must
9292 * copy IPv4 src addr to least
9293 * 32bits in IPv6 address to
9294 * keep traceroute/icmp
9295 * working.
9296 */
9297 pd->nsaddr.addr32[3] =
9298 pd->src->addr32[0];
9299 }
9300 pd->naf = nk->af;
9301 return (PF_AFRT);
9302 }
9303 #endif /* INET && INET6 */
9304
9305 if (PF_ANEQ(pd2.src,
9306 &nk->addr[pd2.sidx], pd2.af) ||
9307 nk->port[pd2.sidx] != sh->src_port)
9308 pf_change_icmp(pd2.src, &sh->src_port,
9309 daddr, &nk->addr[pd2.sidx],
9310 nk->port[pd2.sidx], NULL,
9311 pd2.ip_sum, icmpsum,
9312 pd->ip_sum, 0, pd2.af);
9313
9314 if (PF_ANEQ(pd2.dst,
9315 &nk->addr[pd2.didx], pd2.af) ||
9316 nk->port[pd2.didx] != sh->dest_port)
9317 pf_change_icmp(pd2.dst, &sh->dest_port,
9318 saddr, &nk->addr[pd2.didx],
9319 nk->port[pd2.didx], NULL,
9320 pd2.ip_sum, icmpsum,
9321 pd->ip_sum, 0, pd2.af);
9322 copyback = 1;
9323 }
9324
9325 if (copyback) {
9326 switch (pd2.af) {
9327 #ifdef INET
9328 case AF_INET:
9329 m_copyback(pd->m, pd->off, ICMP_MINLEN,
9330 (caddr_t )&pd->hdr.icmp);
9331 m_copyback(pd->m, ipoff2, sizeof(h2),
9332 (caddr_t )&h2);
9333 break;
9334 #endif /* INET */
9335 #ifdef INET6
9336 case AF_INET6:
9337 m_copyback(pd->m, pd->off,
9338 sizeof(struct icmp6_hdr),
9339 (caddr_t )&pd->hdr.icmp6);
9340 m_copyback(pd->m, ipoff2, sizeof(h2_6),
9341 (caddr_t )&h2_6);
9342 break;
9343 #endif /* INET6 */
9344 }
9345 m_copyback(pd->m, pd2.off, sizeof(*sh), (caddr_t)sh);
9346 }
9347
9348 return (PF_PASS);
9349 break;
9350 }
9351 case IPPROTO_ICMP: {
9352 struct icmp *iih = &pd2.hdr.icmp;
9353
9354 if (pd2.af != AF_INET) {
9355 REASON_SET(reason, PFRES_NORM);
9356 return (PF_DROP);
9357 }
9358
9359 if (!pf_pull_hdr(pd->m, pd2.off, iih, ICMP_MINLEN,
9360 reason, pd2.af)) {
9361 DPFPRINTF(PF_DEBUG_MISC,
9362 "pf: ICMP error message too short i"
9363 "(icmp)");
9364 return (PF_DROP);
9365 }
9366 pd2.pcksum = &pd2.hdr.icmp.icmp_cksum;
9367
9368 icmpid = iih->icmp_id;
9369 pf_icmp_mapping(&pd2, iih->icmp_type,
9370 &icmp_dir, &virtual_id, &virtual_type);
9371
9372 ret = pf_icmp_state_lookup(&key, &pd2, state,
9373 virtual_id, virtual_type, icmp_dir, &iidx, 0, 1);
9374 if (ret >= 0) {
9375 MPASS(*state == NULL);
9376 return (ret);
9377 }
9378
9379 /* translate source/destination address, if necessary */
9380 if ((*state)->key[PF_SK_WIRE] !=
9381 (*state)->key[PF_SK_STACK]) {
9382 struct pf_state_key *nk;
9383
9384 if (PF_REVERSED_KEY(*state, pd->af))
9385 nk = (*state)->key[pd->sidx];
9386 else
9387 nk = (*state)->key[pd->didx];
9388
9389 #if defined(INET) && defined(INET6)
9390 int afto, sidx, didx;
9391
9392 afto = pd->af != nk->af;
9393
9394 if (afto && (*state)->direction == PF_IN) {
9395 sidx = pd2.didx;
9396 didx = pd2.sidx;
9397 iidx = !iidx;
9398 } else {
9399 sidx = pd2.sidx;
9400 didx = pd2.didx;
9401 }
9402
9403 if (afto) {
9404 if (nk->af != AF_INET6)
9405 return (PF_DROP);
9406 if (pf_translate_icmp_af(nk->af,
9407 &pd->hdr.icmp))
9408 return (PF_DROP);
9409 m_copyback(pd->m, pd->off,
9410 sizeof(struct icmp6_hdr),
9411 (c_caddr_t)&pd->hdr.icmp6);
9412 if (pf_change_icmp_af(pd->m, ipoff2, pd,
9413 &pd2, &nk->addr[sidx],
9414 &nk->addr[didx], pd->af,
9415 nk->af))
9416 return (PF_DROP);
9417 pd->proto = IPPROTO_ICMPV6;
9418 if (pf_translate_icmp_af(nk->af, iih))
9419 return (PF_DROP);
9420 if (virtual_type == htons(ICMP_ECHO) &&
9421 nk->port[iidx] != iih->icmp_id)
9422 iih->icmp_id = nk->port[iidx];
9423 m_copyback(pd2.m, pd2.off, ICMP_MINLEN,
9424 (c_caddr_t)iih);
9425 pf_addrcpy(&pd->nsaddr,
9426 &nk->addr[pd2.sidx], nk->af);
9427 pf_addrcpy(&pd->ndaddr,
9428 &nk->addr[pd2.didx], nk->af);
9429 /*
9430 * IPv4 becomes IPv6 so we must copy
9431 * IPv4 src addr to least 32bits in
9432 * IPv6 address to keep traceroute
9433 * working.
9434 */
9435 pd->nsaddr.addr32[3] =
9436 pd->src->addr32[0];
9437 pd->naf = nk->af;
9438 return (PF_AFRT);
9439 }
9440 #endif /* INET && INET6 */
9441
9442 if (PF_ANEQ(pd2.src,
9443 &nk->addr[pd2.sidx], pd2.af) ||
9444 (virtual_type == htons(ICMP_ECHO) &&
9445 nk->port[iidx] != iih->icmp_id))
9446 pf_change_icmp(pd2.src,
9447 (virtual_type == htons(ICMP_ECHO)) ?
9448 &iih->icmp_id : NULL,
9449 daddr, &nk->addr[pd2.sidx],
9450 (virtual_type == htons(ICMP_ECHO)) ?
9451 nk->port[iidx] : 0, NULL,
9452 pd2.ip_sum, icmpsum,
9453 pd->ip_sum, 0, AF_INET);
9454
9455 if (PF_ANEQ(pd2.dst,
9456 &nk->addr[pd2.didx], pd2.af))
9457 pf_change_icmp(pd2.dst, NULL, NULL,
9458 &nk->addr[pd2.didx], 0, NULL,
9459 pd2.ip_sum, icmpsum, pd->ip_sum, 0,
9460 AF_INET);
9461
9462 m_copyback(pd->m, pd->off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
9463 m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
9464 m_copyback(pd->m, pd2.off, ICMP_MINLEN, (caddr_t)iih);
9465 }
9466 return (PF_PASS);
9467 break;
9468 }
9469 #endif /* INET */
9470 #ifdef INET6
9471 case IPPROTO_ICMPV6: {
9472 struct icmp6_hdr *iih = &pd2.hdr.icmp6;
9473
9474 if (pd2.af != AF_INET6) {
9475 REASON_SET(reason, PFRES_NORM);
9476 return (PF_DROP);
9477 }
9478
9479 if (!pf_pull_hdr(pd->m, pd2.off, iih,
9480 sizeof(struct icmp6_hdr), reason, pd2.af)) {
9481 DPFPRINTF(PF_DEBUG_MISC,
9482 "pf: ICMP error message too short "
9483 "(icmp6)");
9484 return (PF_DROP);
9485 }
9486 pd2.pcksum = &pd2.hdr.icmp6.icmp6_cksum;
9487
9488 pf_icmp_mapping(&pd2, iih->icmp6_type,
9489 &icmp_dir, &virtual_id, &virtual_type);
9490
9491 ret = pf_icmp_state_lookup(&key, &pd2, state,
9492 virtual_id, virtual_type, icmp_dir, &iidx, 0, 1);
9493 /* IPv6? try matching a multicast address */
9494 if (ret == PF_DROP && pd2.af == AF_INET6 &&
9495 icmp_dir == PF_OUT) {
9496 MPASS(*state == NULL);
9497 ret = pf_icmp_state_lookup(&key, &pd2,
9498 state, virtual_id, virtual_type,
9499 icmp_dir, &iidx, 1, 1);
9500 }
9501 if (ret >= 0) {
9502 MPASS(*state == NULL);
9503 return (ret);
9504 }
9505
9506 /* translate source/destination address, if necessary */
9507 if ((*state)->key[PF_SK_WIRE] !=
9508 (*state)->key[PF_SK_STACK]) {
9509 struct pf_state_key *nk;
9510
9511 if (PF_REVERSED_KEY(*state, pd->af))
9512 nk = (*state)->key[pd->sidx];
9513 else
9514 nk = (*state)->key[pd->didx];
9515
9516 #if defined(INET) && defined(INET6)
9517 int afto, sidx, didx;
9518
9519 afto = pd->af != nk->af;
9520
9521 if (afto && (*state)->direction == PF_IN) {
9522 sidx = pd2.didx;
9523 didx = pd2.sidx;
9524 iidx = !iidx;
9525 } else {
9526 sidx = pd2.sidx;
9527 didx = pd2.didx;
9528 }
9529
9530 if (afto) {
9531 if (nk->af != AF_INET)
9532 return (PF_DROP);
9533 if (pf_translate_icmp_af(nk->af,
9534 &pd->hdr.icmp))
9535 return (PF_DROP);
9536 m_copyback(pd->m, pd->off,
9537 sizeof(struct icmp6_hdr),
9538 (c_caddr_t)&pd->hdr.icmp6);
9539 if (pf_change_icmp_af(pd->m, ipoff2, pd,
9540 &pd2, &nk->addr[sidx],
9541 &nk->addr[didx], pd->af,
9542 nk->af))
9543 return (PF_DROP);
9544 pd->proto = IPPROTO_ICMP;
9545 if (pf_translate_icmp_af(nk->af, iih))
9546 return (PF_DROP);
9547 if (virtual_type ==
9548 htons(ICMP6_ECHO_REQUEST) &&
9549 nk->port[iidx] != iih->icmp6_id)
9550 iih->icmp6_id = nk->port[iidx];
9551 m_copyback(pd2.m, pd2.off,
9552 sizeof(struct icmp6_hdr), (c_caddr_t)iih);
9553 pf_addrcpy(&pd->nsaddr,
9554 &nk->addr[pd2.sidx], nk->af);
9555 pf_addrcpy(&pd->ndaddr,
9556 &nk->addr[pd2.didx], nk->af);
9557 pd->naf = nk->af;
9558 return (PF_AFRT);
9559 }
9560 #endif /* INET && INET6 */
9561
9562 if (PF_ANEQ(pd2.src,
9563 &nk->addr[pd2.sidx], pd2.af) ||
9564 ((virtual_type == htons(ICMP6_ECHO_REQUEST)) &&
9565 nk->port[pd2.sidx] != iih->icmp6_id))
9566 pf_change_icmp(pd2.src,
9567 (virtual_type == htons(ICMP6_ECHO_REQUEST))
9568 ? &iih->icmp6_id : NULL,
9569 daddr, &nk->addr[pd2.sidx],
9570 (virtual_type == htons(ICMP6_ECHO_REQUEST))
9571 ? nk->port[iidx] : 0, NULL,
9572 pd2.ip_sum, icmpsum,
9573 pd->ip_sum, 0, AF_INET6);
9574
9575 if (PF_ANEQ(pd2.dst,
9576 &nk->addr[pd2.didx], pd2.af))
9577 pf_change_icmp(pd2.dst, NULL, NULL,
9578 &nk->addr[pd2.didx], 0, NULL,
9579 pd2.ip_sum, icmpsum,
9580 pd->ip_sum, 0, AF_INET6);
9581
9582 m_copyback(pd->m, pd->off, sizeof(struct icmp6_hdr),
9583 (caddr_t)&pd->hdr.icmp6);
9584 m_copyback(pd->m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
9585 m_copyback(pd->m, pd2.off, sizeof(struct icmp6_hdr),
9586 (caddr_t)iih);
9587 }
9588 return (PF_PASS);
9589 break;
9590 }
9591 #endif /* INET6 */
9592 default: {
9593 int action;
9594
9595 /*
9596 * Placeholder value, so future calls to pf_change_ap()
9597 * don't try to update a NULL checksum pointer.
9598 */
9599 pd->pcksum = &pd->sctp_dummy_sum;
9600 key.af = pd2.af;
9601 key.proto = pd2.proto;
9602 pf_addrcpy(&key.addr[pd2.sidx], pd2.src, key.af);
9603 pf_addrcpy(&key.addr[pd2.didx], pd2.dst, key.af);
9604 key.port[0] = key.port[1] = 0;
9605
9606 action = pf_find_state(&pd2, &key, state);
9607 if (action != PF_MATCH && action != PF_PASS)
9608 return (action);
9609
9610 /* translate source/destination address, if necessary */
9611 if ((*state)->key[PF_SK_WIRE] !=
9612 (*state)->key[PF_SK_STACK]) {
9613 struct pf_state_key *nk =
9614 (*state)->key[pd->didx];
9615
9616 if (PF_ANEQ(pd2.src,
9617 &nk->addr[pd2.sidx], pd2.af))
9618 pf_change_icmp(pd2.src, NULL, daddr,
9619 &nk->addr[pd2.sidx], 0, NULL,
9620 pd2.ip_sum, icmpsum,
9621 pd->ip_sum, 0, pd2.af);
9622
9623 if (PF_ANEQ(pd2.dst,
9624 &nk->addr[pd2.didx], pd2.af))
9625 pf_change_icmp(pd2.dst, NULL, saddr,
9626 &nk->addr[pd2.didx], 0, NULL,
9627 pd2.ip_sum, icmpsum,
9628 pd->ip_sum, 0, pd2.af);
9629
9630 switch (pd2.af) {
9631 #ifdef INET
9632 case AF_INET:
9633 m_copyback(pd->m, pd->off, ICMP_MINLEN,
9634 (caddr_t)&pd->hdr.icmp);
9635 m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
9636 break;
9637 #endif /* INET */
9638 #ifdef INET6
9639 case AF_INET6:
9640 m_copyback(pd->m, pd->off,
9641 sizeof(struct icmp6_hdr),
9642 (caddr_t )&pd->hdr.icmp6);
9643 m_copyback(pd->m, ipoff2, sizeof(h2_6),
9644 (caddr_t )&h2_6);
9645 break;
9646 #endif /* INET6 */
9647 }
9648 }
9649 return (PF_PASS);
9650 break;
9651 }
9652 }
9653 }
9654 }
9655
9656 /*
9657 * ipoff and off are measured from the start of the mbuf chain.
9658 * h must be at "ipoff" on the mbuf chain.
9659 */
9660 void *
pf_pull_hdr(const struct mbuf * m,int off,void * p,int len,u_short * reasonp,sa_family_t af)9661 pf_pull_hdr(const struct mbuf *m, int off, void *p, int len,
9662 u_short *reasonp, sa_family_t af)
9663 {
9664 int iplen = 0;
9665 switch (af) {
9666 #ifdef INET
9667 case AF_INET: {
9668 const struct ip *h = mtod(m, struct ip *);
9669 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
9670
9671 if (fragoff) {
9672 REASON_SET(reasonp, PFRES_FRAG);
9673 return (NULL);
9674 }
9675 iplen = ntohs(h->ip_len);
9676 break;
9677 }
9678 #endif /* INET */
9679 #ifdef INET6
9680 case AF_INET6: {
9681 const struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
9682
9683 iplen = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
9684 break;
9685 }
9686 #endif /* INET6 */
9687 }
9688 if (m->m_pkthdr.len < off + len || iplen < off + len) {
9689 REASON_SET(reasonp, PFRES_SHORT);
9690 return (NULL);
9691 }
9692 m_copydata(m, off, len, p);
9693 return (p);
9694 }
9695
9696 int
pf_routable(struct pf_addr * addr,sa_family_t af,struct pfi_kkif * kif,int rtableid)9697 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kkif *kif,
9698 int rtableid)
9699 {
9700 struct ifnet *ifp;
9701
9702 /*
9703 * Skip check for addresses with embedded interface scope,
9704 * as they would always match anyway.
9705 */
9706 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
9707 return (1);
9708
9709 if (af != AF_INET && af != AF_INET6)
9710 return (0);
9711
9712 if (kif == V_pfi_all)
9713 return (1);
9714
9715 /* Skip checks for ipsec interfaces */
9716 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
9717 return (1);
9718
9719 ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
9720
9721 switch (af) {
9722 #ifdef INET6
9723 case AF_INET6:
9724 return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
9725 ifp));
9726 #endif /* INET6 */
9727 #ifdef INET
9728 case AF_INET:
9729 return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
9730 ifp));
9731 #endif /* INET */
9732 }
9733
9734 return (0);
9735 }
9736
9737 #ifdef INET
9738 static int
pf_route(struct pf_krule * r,struct ifnet * oifp,struct pf_kstate * s,struct pf_pdesc * pd,struct inpcb * inp)9739 pf_route(struct pf_krule *r, struct ifnet *oifp,
9740 struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
9741 {
9742 struct mbuf *m0, *m1, *md;
9743 struct route_in6 ro;
9744 union sockaddr_union rt_gw;
9745 const union sockaddr_union *gw = (const union sockaddr_union *)&ro.ro_dst;
9746 union sockaddr_union *dst;
9747 struct ip *ip;
9748 struct ifnet *ifp = NULL;
9749 int error = 0;
9750 uint16_t ip_len, ip_off;
9751 uint16_t tmp;
9752 int r_dir;
9753 bool skip_test = false;
9754 int action = PF_PASS;
9755
9756 KASSERT(pd->m && r && oifp, ("%s: invalid parameters", __func__));
9757
9758 SDT_PROBE4(pf, ip, route_to, entry, pd->m, pd, s, oifp);
9759
9760 if (s) {
9761 r_dir = s->direction;
9762 } else {
9763 r_dir = r->direction;
9764 }
9765
9766 KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
9767 r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
9768 __func__));
9769
9770 if ((pd->pf_mtag == NULL &&
9771 ((pd->pf_mtag = pf_get_mtag(pd->m)) == NULL)) ||
9772 pd->pf_mtag->routed++ > 3) {
9773 m0 = pd->m;
9774 pd->m = NULL;
9775 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9776 action = PF_DROP;
9777 goto bad_locked;
9778 }
9779
9780 if (pd->act.rt_kif != NULL)
9781 ifp = pd->act.rt_kif->pfik_ifp;
9782
9783 if (pd->act.rt == PF_DUPTO) {
9784 if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
9785 if (s != NULL) {
9786 PF_STATE_UNLOCK(s);
9787 }
9788 if (ifp == oifp) {
9789 /* When the 2nd interface is not skipped */
9790 return (action);
9791 } else {
9792 m0 = pd->m;
9793 pd->m = NULL;
9794 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9795 action = PF_DROP;
9796 goto bad;
9797 }
9798 } else {
9799 pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
9800 if (((m0 = m_dup(pd->m, M_NOWAIT)) == NULL)) {
9801 if (s)
9802 PF_STATE_UNLOCK(s);
9803 return (action);
9804 }
9805 }
9806 } else {
9807 if ((pd->act.rt == PF_REPLYTO) == (r_dir == pd->dir)) {
9808 if (pd->af == pd->naf) {
9809 pf_dummynet(pd, s, r, &pd->m);
9810 if (s)
9811 PF_STATE_UNLOCK(s);
9812 return (action);
9813 } else {
9814 if (r_dir == PF_IN) {
9815 skip_test = true;
9816 }
9817 }
9818 }
9819
9820 /*
9821 * If we're actually doing route-to and af-to and are in the
9822 * reply direction.
9823 */
9824 if (pd->act.rt_kif && pd->act.rt_kif->pfik_ifp &&
9825 pd->af != pd->naf) {
9826 if (pd->act.rt == PF_ROUTETO && r->naf != AF_INET) {
9827 /* Un-set ifp so we do a plain route lookup. */
9828 ifp = NULL;
9829 }
9830 if (pd->act.rt == PF_REPLYTO && r->naf != AF_INET6) {
9831 /* Un-set ifp so we do a plain route lookup. */
9832 ifp = NULL;
9833 }
9834 }
9835 m0 = pd->m;
9836 }
9837
9838 ip = mtod(m0, struct ip *);
9839
9840 bzero(&ro, sizeof(ro));
9841 dst = (union sockaddr_union *)&ro.ro_dst;
9842 dst->sin.sin_family = AF_INET;
9843 dst->sin.sin_len = sizeof(struct sockaddr_in);
9844 dst->sin.sin_addr = ip->ip_dst;
9845 if (ifp) { /* Only needed in forward direction and route-to */
9846 bzero(&rt_gw, sizeof(rt_gw));
9847 ro.ro_flags |= RT_HAS_GW;
9848 gw = &rt_gw;
9849 switch (pd->act.rt_af) {
9850 #ifdef INET
9851 case AF_INET:
9852 rt_gw.sin.sin_family = AF_INET;
9853 rt_gw.sin.sin_len = sizeof(struct sockaddr_in);
9854 rt_gw.sin.sin_addr.s_addr = pd->act.rt_addr.v4.s_addr;
9855 break;
9856 #endif /* INET */
9857 #ifdef INET6
9858 case AF_INET6:
9859 rt_gw.sin6.sin6_family = AF_INET6;
9860 rt_gw.sin6.sin6_len = sizeof(struct sockaddr_in6);
9861 pf_addrcpy((struct pf_addr *)&rt_gw.sin6.sin6_addr,
9862 &pd->act.rt_addr, AF_INET6);
9863 break;
9864 #endif /* INET6 */
9865 default:
9866 /* Normal af-to without route-to */
9867 break;
9868 }
9869 }
9870
9871 if (pd->dir == PF_IN) {
9872 if (ip->ip_ttl <= IPTTLDEC) {
9873 if (r->rt != PF_DUPTO && pd->naf == pd->af)
9874 pf_send_icmp(m0, ICMP_TIMXCEED,
9875 ICMP_TIMXCEED_INTRANS, 0, pd->af, r,
9876 pd->act.rtableid);
9877 action = PF_DROP;
9878 goto bad_locked;
9879 }
9880 ip->ip_ttl -= IPTTLDEC;
9881 }
9882
9883 if (s != NULL) {
9884 if (ifp == NULL && (pd->af != pd->naf)) {
9885 /* We're in the AFTO case. Do a route lookup. */
9886 const struct nhop_object *nh;
9887 nh = fib4_lookup(M_GETFIB(m0), ip->ip_dst, 0, NHR_NONE, 0);
9888 if (nh) {
9889 ifp = nh->nh_ifp;
9890
9891 /* Use the gateway if needed. */
9892 if (nh->nh_flags & NHF_GATEWAY) {
9893 gw = (const union sockaddr_union *)&nh->gw_sa;
9894 ro.ro_flags |= RT_HAS_GW;
9895 } else {
9896 dst->sin.sin_addr = ip->ip_dst;
9897 }
9898 }
9899 }
9900 PF_STATE_UNLOCK(s);
9901 }
9902
9903 /* It must have been either set from rt_af or from fib4_lookup */
9904 KASSERT(gw->sin.sin_family != 0, ("%s: gw address family undetermined", __func__));
9905
9906 if (ifp == NULL) {
9907 m0 = pd->m;
9908 pd->m = NULL;
9909 action = PF_DROP;
9910 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9911 goto bad;
9912 }
9913
9914 /*
9915 * Bind to the correct interface if we're if-bound. We don't know which
9916 * interface that will be until here, so we've inserted the state
9917 * on V_pf_all. Fix that now.
9918 */
9919 if (s != NULL && s->kif == V_pfi_all && r->rule_flag & PFRULE_IFBOUND) {
9920 /* Verify that we're here because of BOUND_IFACE */
9921 MPASS(r->rt == PF_REPLYTO || (pd->af != pd->naf && s->direction == PF_IN));
9922 s->kif = ifp->if_pf_kif;
9923 if (pd->act.rt == PF_REPLYTO) {
9924 s->orig_kif = oifp->if_pf_kif;
9925 }
9926 }
9927
9928 if (r->rt == PF_DUPTO || (pd->af != pd->naf && s->direction == PF_IN))
9929 skip_test = true;
9930
9931 if (pd->dir == PF_IN) {
9932 if (skip_test) {
9933 struct pfi_kkif *out_kif = (struct pfi_kkif *)ifp->if_pf_kif;
9934 MPASS(s != NULL);
9935 pf_counter_u64_critical_enter();
9936 pf_counter_u64_add_protected(
9937 &out_kif->pfik_bytes[pd->naf == AF_INET6][1]
9938 [action != PF_PASS && action != PF_AFRT], pd->tot_len);
9939 pf_counter_u64_add_protected(
9940 &out_kif->pfik_packets[pd->naf == AF_INET6][1]
9941 [action != PF_PASS && action != PF_AFRT], 1);
9942 pf_counter_u64_critical_exit();
9943 } else {
9944 if (pf_test(AF_INET, PF_OUT, PFIL_FWD, ifp, &m0, inp,
9945 &pd->act) != PF_PASS) {
9946 action = PF_DROP;
9947 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9948 goto bad;
9949 } else if (m0 == NULL) {
9950 action = PF_DROP;
9951 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9952 goto done;
9953 }
9954 if (m0->m_len < sizeof(struct ip)) {
9955 DPFPRINTF(PF_DEBUG_URGENT,
9956 "%s: m0->m_len < sizeof(struct ip)", __func__);
9957 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9958 action = PF_DROP;
9959 goto bad;
9960 }
9961 ip = mtod(m0, struct ip *);
9962 }
9963 }
9964
9965 if (ifp->if_flags & IFF_LOOPBACK)
9966 m0->m_flags |= M_SKIP_FIREWALL;
9967
9968 ip_len = ntohs(ip->ip_len);
9969 ip_off = ntohs(ip->ip_off);
9970
9971 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
9972 m0->m_pkthdr.csum_flags |= CSUM_IP;
9973 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
9974 in_delayed_cksum(m0);
9975 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
9976 }
9977 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
9978 pf_sctp_checksum(m0, (uint32_t)(ip->ip_hl << 2));
9979 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
9980 }
9981
9982 if (pd->dir == PF_IN) {
9983 /*
9984 * Make sure dummynet gets the correct direction, in case it needs to
9985 * re-inject later.
9986 */
9987 pd->dir = PF_OUT;
9988
9989 /*
9990 * The following processing is actually the rest of the inbound processing, even
9991 * though we've marked it as outbound (so we don't look through dummynet) and it
9992 * happens after the outbound processing (pf_test(PF_OUT) above).
9993 * Swap the dummynet pipe numbers, because it's going to come to the wrong
9994 * conclusion about what direction it's processing, and we can't fix it or it
9995 * will re-inject incorrectly. Swapping the pipe numbers means that its incorrect
9996 * decision will pick the right pipe, and everything will mostly work as expected.
9997 */
9998 tmp = pd->act.dnrpipe;
9999 pd->act.dnrpipe = pd->act.dnpipe;
10000 pd->act.dnpipe = tmp;
10001 }
10002
10003 /*
10004 * If the output interface does not accept unmapped mbufs, convert
10005 * them to mapped mbufs.
10006 */
10007 if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
10008 error = mb_unmapped_to_ext(m0, &md);
10009 if (error)
10010 goto done;
10011 /*
10012 * The first mbuf should not be reallocated because it is
10013 * always mapped.
10014 */
10015 MPASS(m0 == md);
10016 }
10017
10018 /*
10019 * If small enough for interface, or the interface will take
10020 * care of the fragmentation for us, we can just send directly.
10021 */
10022 if (ip_len <= ifp->if_mtu ||
10023 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
10024 ip->ip_sum = 0;
10025 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
10026 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
10027 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
10028 }
10029 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
10030
10031 md = m0;
10032 error = pf_dummynet_route(pd, s, r, ifp,
10033 (const struct sockaddr *)gw, &md);
10034 if (md != NULL) {
10035 error = (*ifp->if_output)(ifp, md,
10036 (const struct sockaddr *)gw, (struct route *)&ro);
10037 SDT_PROBE2(pf, ip, route_to, output, ifp, error);
10038 }
10039 goto done;
10040 }
10041
10042 /* Balk when DF bit is set or the interface didn't support TSO. */
10043 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
10044 error = EMSGSIZE;
10045 KMOD_IPSTAT_INC(ips_cantfrag);
10046 if (pd->act.rt != PF_DUPTO) {
10047 if (s && s->nat_rule != NULL) {
10048 MPASS(m0 == pd->m);
10049 PACKET_UNDO_NAT(pd,
10050 (ip->ip_hl << 2) + (ip_off & IP_OFFMASK),
10051 s);
10052 }
10053
10054 pf_send_icmp(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG,
10055 ifp->if_mtu, pd->af, r, pd->act.rtableid);
10056 }
10057 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
10058 /* Return pass, so we return PFIL_CONSUMED to the stack. */
10059 action = PF_PASS;
10060 goto bad;
10061 }
10062
10063 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
10064 if (error) {
10065 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
10066 action = PF_DROP;
10067 goto bad;
10068 }
10069
10070 for (; m0; m0 = m1) {
10071 m1 = m0->m_nextpkt;
10072 m0->m_nextpkt = NULL;
10073 if (error == 0) {
10074 m_clrprotoflags(m0);
10075 md = m0;
10076 pd->pf_mtag = pf_find_mtag(md);
10077 error = pf_dummynet_route(pd, s, r, ifp,
10078 (const struct sockaddr *)gw, &md);
10079 if (md != NULL) {
10080 error = (*ifp->if_output)(ifp, md,
10081 (const struct sockaddr *)gw,
10082 (struct route *)&ro);
10083 SDT_PROBE2(pf, ip, route_to, output, ifp, error);
10084 }
10085 } else
10086 m_freem(m0);
10087 }
10088
10089 if (error == 0)
10090 KMOD_IPSTAT_INC(ips_fragmented);
10091
10092 done:
10093 if (pd->act.rt != PF_DUPTO)
10094 pd->m = NULL;
10095 else
10096 action = PF_PASS;
10097 return (action);
10098
10099 bad_locked:
10100 if (s)
10101 PF_STATE_UNLOCK(s);
10102 bad:
10103 m_freem(m0);
10104 goto done;
10105 }
10106 #endif /* INET */
10107
10108 #ifdef INET6
10109 static int
pf_route6(struct pf_krule * r,struct ifnet * oifp,struct pf_kstate * s,struct pf_pdesc * pd,struct inpcb * inp)10110 pf_route6(struct pf_krule *r, struct ifnet *oifp,
10111 struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
10112 {
10113 struct mbuf *m0, *md;
10114 struct m_tag *mtag;
10115 struct sockaddr_in6 dst;
10116 struct ip6_hdr *ip6;
10117 struct ifnet *ifp = NULL;
10118 int r_dir;
10119 bool skip_test = false;
10120 int action = PF_PASS;
10121
10122 KASSERT(pd->m && r && oifp, ("%s: invalid parameters", __func__));
10123
10124 SDT_PROBE4(pf, ip6, route_to, entry, pd->m, pd, s, oifp);
10125
10126 if (s) {
10127 r_dir = s->direction;
10128 } else {
10129 r_dir = r->direction;
10130 }
10131
10132 KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
10133 r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
10134 __func__));
10135
10136 if ((pd->pf_mtag == NULL &&
10137 ((pd->pf_mtag = pf_get_mtag(pd->m)) == NULL)) ||
10138 pd->pf_mtag->routed++ > 3) {
10139 m0 = pd->m;
10140 pd->m = NULL;
10141 action = PF_DROP;
10142 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
10143 goto bad_locked;
10144 }
10145
10146 if (pd->act.rt_kif != NULL)
10147 ifp = pd->act.rt_kif->pfik_ifp;
10148
10149 if (pd->act.rt == PF_DUPTO) {
10150 if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
10151 if (s != NULL) {
10152 PF_STATE_UNLOCK(s);
10153 }
10154 if (ifp == oifp) {
10155 /* When the 2nd interface is not skipped */
10156 return (action);
10157 } else {
10158 m0 = pd->m;
10159 pd->m = NULL;
10160 action = PF_DROP;
10161 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
10162 goto bad;
10163 }
10164 } else {
10165 pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
10166 if (((m0 = m_dup(pd->m, M_NOWAIT)) == NULL)) {
10167 if (s)
10168 PF_STATE_UNLOCK(s);
10169 return (action);
10170 }
10171 }
10172 } else {
10173 if ((pd->act.rt == PF_REPLYTO) == (r_dir == pd->dir)) {
10174 if (pd->af == pd->naf) {
10175 pf_dummynet(pd, s, r, &pd->m);
10176 if (s)
10177 PF_STATE_UNLOCK(s);
10178 return (action);
10179 } else {
10180 if (r_dir == PF_IN) {
10181 skip_test = true;
10182 }
10183 }
10184 }
10185
10186 /*
10187 * If we're actually doing route-to and af-to and are in the
10188 * reply direction.
10189 */
10190 if (pd->act.rt_kif && pd->act.rt_kif->pfik_ifp &&
10191 pd->af != pd->naf) {
10192 if (pd->act.rt == PF_ROUTETO && r->naf != AF_INET6) {
10193 /* Un-set ifp so we do a plain route lookup. */
10194 ifp = NULL;
10195 }
10196 if (pd->act.rt == PF_REPLYTO && r->naf != AF_INET) {
10197 /* Un-set ifp so we do a plain route lookup. */
10198 ifp = NULL;
10199 }
10200 }
10201 m0 = pd->m;
10202 }
10203
10204 ip6 = mtod(m0, struct ip6_hdr *);
10205
10206 bzero(&dst, sizeof(dst));
10207 dst.sin6_family = AF_INET6;
10208 dst.sin6_len = sizeof(dst);
10209 pf_addrcpy((struct pf_addr *)&dst.sin6_addr, &pd->act.rt_addr,
10210 AF_INET6);
10211
10212 if (pd->dir == PF_IN) {
10213 if (ip6->ip6_hlim <= IPV6_HLIMDEC) {
10214 if (r->rt != PF_DUPTO && pd->naf == pd->af)
10215 pf_send_icmp(m0, ICMP6_TIME_EXCEEDED,
10216 ICMP6_TIME_EXCEED_TRANSIT, 0, pd->af, r,
10217 pd->act.rtableid);
10218 action = PF_DROP;
10219 goto bad_locked;
10220 }
10221 ip6->ip6_hlim -= IPV6_HLIMDEC;
10222 }
10223
10224 if (s != NULL) {
10225 if (ifp == NULL && (pd->af != pd->naf)) {
10226 const struct nhop_object *nh;
10227 nh = fib6_lookup(M_GETFIB(m0), &ip6->ip6_dst, 0, NHR_NONE, 0);
10228 if (nh) {
10229 ifp = nh->nh_ifp;
10230
10231 /* Use the gateway if needed. */
10232 if (nh->nh_flags & NHF_GATEWAY)
10233 bcopy(&nh->gw6_sa.sin6_addr, &dst.sin6_addr,
10234 sizeof(dst.sin6_addr));
10235 else
10236 dst.sin6_addr = ip6->ip6_dst;
10237 }
10238 }
10239 PF_STATE_UNLOCK(s);
10240 }
10241
10242 if (pd->af != pd->naf) {
10243 struct udphdr *uh = &pd->hdr.udp;
10244
10245 if (pd->proto == IPPROTO_UDP && uh->uh_sum == 0) {
10246 uh->uh_sum = in6_cksum_pseudo(ip6,
10247 ntohs(uh->uh_ulen), IPPROTO_UDP, 0);
10248 m_copyback(m0, pd->off, sizeof(*uh), pd->hdr.any);
10249 }
10250 }
10251
10252 if (ifp == NULL) {
10253 m0 = pd->m;
10254 pd->m = NULL;
10255 action = PF_DROP;
10256 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
10257 goto bad;
10258 }
10259
10260 /*
10261 * Bind to the correct interface if we're if-bound. We don't know which
10262 * interface that will be until here, so we've inserted the state
10263 * on V_pf_all. Fix that now.
10264 */
10265 if (s != NULL && s->kif == V_pfi_all && r->rule_flag & PFRULE_IFBOUND) {
10266 /* Verify that we're here because of BOUND_IFACE */
10267 MPASS(r->rt == PF_REPLYTO || (pd->af != pd->naf && s->direction == PF_IN));
10268 s->kif = ifp->if_pf_kif;
10269 if (pd->act.rt == PF_REPLYTO) {
10270 s->orig_kif = oifp->if_pf_kif;
10271 }
10272 }
10273
10274 if (r->rt == PF_DUPTO || (pd->af != pd->naf && s->direction == PF_IN))
10275 skip_test = true;
10276
10277 if (pd->dir == PF_IN) {
10278 if (skip_test) {
10279 struct pfi_kkif *out_kif = (struct pfi_kkif *)ifp->if_pf_kif;
10280 MPASS(s != NULL);
10281 pf_counter_u64_critical_enter();
10282 pf_counter_u64_add_protected(
10283 &out_kif->pfik_bytes[pd->naf == AF_INET6][1]
10284 [action != PF_PASS && action != PF_AFRT], pd->tot_len);
10285 pf_counter_u64_add_protected(
10286 &out_kif->pfik_packets[pd->naf == AF_INET6][1]
10287 [action != PF_PASS && action != PF_AFRT], 1);
10288 pf_counter_u64_critical_exit();
10289 } else {
10290 if (pf_test(AF_INET6, PF_OUT, PFIL_FWD | PF_PFIL_NOREFRAGMENT,
10291 ifp, &m0, inp, &pd->act) != PF_PASS) {
10292 action = PF_DROP;
10293 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
10294 goto bad;
10295 } else if (m0 == NULL) {
10296 action = PF_DROP;
10297 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
10298 goto done;
10299 }
10300 if (m0->m_len < sizeof(struct ip6_hdr)) {
10301 DPFPRINTF(PF_DEBUG_URGENT,
10302 "%s: m0->m_len < sizeof(struct ip6_hdr)",
10303 __func__);
10304 action = PF_DROP;
10305 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
10306 goto bad;
10307 }
10308 ip6 = mtod(m0, struct ip6_hdr *);
10309 }
10310 }
10311
10312 if (ifp->if_flags & IFF_LOOPBACK)
10313 m0->m_flags |= M_SKIP_FIREWALL;
10314
10315 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
10316 ~ifp->if_hwassist) {
10317 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
10318 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
10319 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
10320 }
10321
10322 if (pd->dir == PF_IN) {
10323 uint16_t tmp;
10324 /*
10325 * Make sure dummynet gets the correct direction, in case it needs to
10326 * re-inject later.
10327 */
10328 pd->dir = PF_OUT;
10329
10330 /*
10331 * The following processing is actually the rest of the inbound processing, even
10332 * though we've marked it as outbound (so we don't look through dummynet) and it
10333 * happens after the outbound processing (pf_test(PF_OUT) above).
10334 * Swap the dummynet pipe numbers, because it's going to come to the wrong
10335 * conclusion about what direction it's processing, and we can't fix it or it
10336 * will re-inject incorrectly. Swapping the pipe numbers means that its incorrect
10337 * decision will pick the right pipe, and everything will mostly work as expected.
10338 */
10339 tmp = pd->act.dnrpipe;
10340 pd->act.dnrpipe = pd->act.dnpipe;
10341 pd->act.dnpipe = tmp;
10342 }
10343
10344 /*
10345 * If the packet is too large for the outgoing interface,
10346 * send back an icmp6 error.
10347 */
10348 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
10349 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
10350 mtag = m_tag_find(m0, PACKET_TAG_PF_REASSEMBLED, NULL);
10351 if (mtag != NULL) {
10352 int ret __sdt_used;
10353 ret = pf_refragment6(ifp, &m0, mtag, ifp, true);
10354 SDT_PROBE2(pf, ip6, route_to, output, ifp, ret);
10355 goto done;
10356 }
10357
10358 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
10359 if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
10360 if (mb_unmapped_to_ext(m0, &md) != 0)
10361 goto done;
10362 MPASS(m0 == md);
10363 }
10364 md = m0;
10365 pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
10366 if (md != NULL) {
10367 int ret __sdt_used;
10368 ret = nd6_output_ifp(ifp, ifp, md, &dst, NULL);
10369 SDT_PROBE2(pf, ip6, route_to, output, ifp, ret);
10370 }
10371 }
10372 else {
10373 in6_ifstat_inc(ifp, ifs6_in_toobig);
10374 if (pd->act.rt != PF_DUPTO) {
10375 if (s && s->nat_rule != NULL) {
10376 MPASS(m0 == pd->m);
10377 PACKET_UNDO_NAT(pd,
10378 ((caddr_t)ip6 - m0->m_data) +
10379 sizeof(struct ip6_hdr), s);
10380 }
10381
10382 if (r->rt != PF_DUPTO)
10383 pf_send_icmp(m0, ICMP6_PACKET_TOO_BIG, 0,
10384 ifp->if_mtu, pd->af, r, pd->act.rtableid);
10385 }
10386 /* Return pass, so we return PFIL_CONSUMED to the stack. */
10387 action = PF_PASS;
10388 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
10389 goto bad;
10390 }
10391
10392 done:
10393 if (pd->act.rt != PF_DUPTO)
10394 pd->m = NULL;
10395 else
10396 action = PF_PASS;
10397 return (action);
10398
10399 bad_locked:
10400 if (s)
10401 PF_STATE_UNLOCK(s);
10402 bad:
10403 m_freem(m0);
10404 goto done;
10405 }
10406 #endif /* INET6 */
10407
10408 /*
10409 * FreeBSD supports cksum offloads for the following drivers.
10410 * em(4), fxp(4), lge(4), nge(4), re(4), ti(4), txp(4), xl(4)
10411 *
10412 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
10413 * network driver performed cksum including pseudo header, need to verify
10414 * csum_data
10415 * CSUM_DATA_VALID :
10416 * network driver performed cksum, needs to additional pseudo header
10417 * cksum computation with partial csum_data(i.e. lack of H/W support for
10418 * pseudo header, for instance sk(4) and possibly gem(4))
10419 *
10420 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
10421 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
10422 * TCP/UDP layer.
10423 * Also, set csum_data to 0xffff to force cksum validation.
10424 */
10425 static int
pf_check_proto_cksum(struct mbuf * m,int off,int len,u_int8_t p,sa_family_t af)10426 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
10427 {
10428 u_int16_t sum = 0;
10429 int hw_assist = 0;
10430 struct ip *ip;
10431
10432 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
10433 return (1);
10434 if (m->m_pkthdr.len < off + len)
10435 return (1);
10436
10437 switch (p) {
10438 case IPPROTO_TCP:
10439 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
10440 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
10441 sum = m->m_pkthdr.csum_data;
10442 } else {
10443 ip = mtod(m, struct ip *);
10444 sum = in_pseudo(ip->ip_src.s_addr,
10445 ip->ip_dst.s_addr, htonl((u_short)len +
10446 m->m_pkthdr.csum_data + IPPROTO_TCP));
10447 }
10448 sum ^= 0xffff;
10449 ++hw_assist;
10450 }
10451 break;
10452 case IPPROTO_UDP:
10453 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
10454 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
10455 sum = m->m_pkthdr.csum_data;
10456 } else {
10457 ip = mtod(m, struct ip *);
10458 sum = in_pseudo(ip->ip_src.s_addr,
10459 ip->ip_dst.s_addr, htonl((u_short)len +
10460 m->m_pkthdr.csum_data + IPPROTO_UDP));
10461 }
10462 sum ^= 0xffff;
10463 ++hw_assist;
10464 }
10465 break;
10466 case IPPROTO_ICMP:
10467 #ifdef INET6
10468 case IPPROTO_ICMPV6:
10469 #endif /* INET6 */
10470 break;
10471 default:
10472 return (1);
10473 }
10474
10475 if (!hw_assist) {
10476 switch (af) {
10477 case AF_INET:
10478 if (m->m_len < sizeof(struct ip))
10479 return (1);
10480 sum = in4_cksum(m, (p == IPPROTO_ICMP ? 0 : p), off, len);
10481 break;
10482 #ifdef INET6
10483 case AF_INET6:
10484 if (m->m_len < sizeof(struct ip6_hdr))
10485 return (1);
10486 sum = in6_cksum(m, p, off, len);
10487 break;
10488 #endif /* INET6 */
10489 }
10490 }
10491 if (sum) {
10492 switch (p) {
10493 case IPPROTO_TCP:
10494 {
10495 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
10496 break;
10497 }
10498 case IPPROTO_UDP:
10499 {
10500 KMOD_UDPSTAT_INC(udps_badsum);
10501 break;
10502 }
10503 #ifdef INET
10504 case IPPROTO_ICMP:
10505 {
10506 KMOD_ICMPSTAT_INC(icps_checksum);
10507 break;
10508 }
10509 #endif
10510 #ifdef INET6
10511 case IPPROTO_ICMPV6:
10512 {
10513 KMOD_ICMP6STAT_INC(icp6s_checksum);
10514 break;
10515 }
10516 #endif /* INET6 */
10517 }
10518 return (1);
10519 } else {
10520 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
10521 m->m_pkthdr.csum_flags |=
10522 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
10523 m->m_pkthdr.csum_data = 0xffff;
10524 }
10525 }
10526 return (0);
10527 }
10528
10529 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)10530 pf_pdesc_to_dnflow(const struct pf_pdesc *pd, const struct pf_krule *r,
10531 const struct pf_kstate *s, struct ip_fw_args *dnflow)
10532 {
10533 int dndir = r->direction;
10534 sa_family_t af = pd->naf;
10535
10536 if (s && dndir == PF_INOUT) {
10537 dndir = s->direction;
10538 } else if (dndir == PF_INOUT) {
10539 /* Assume primary direction. Happens when we've set dnpipe in
10540 * the ethernet level code. */
10541 dndir = pd->dir;
10542 }
10543
10544 if (pd->pf_mtag->flags & PF_MTAG_FLAG_DUMMYNETED)
10545 return (false);
10546
10547 memset(dnflow, 0, sizeof(*dnflow));
10548
10549 if (pd->dport != NULL)
10550 dnflow->f_id.dst_port = ntohs(*pd->dport);
10551 if (pd->sport != NULL)
10552 dnflow->f_id.src_port = ntohs(*pd->sport);
10553
10554 if (pd->dir == PF_IN)
10555 dnflow->flags |= IPFW_ARGS_IN;
10556 else
10557 dnflow->flags |= IPFW_ARGS_OUT;
10558
10559 if (pd->dir != dndir && pd->act.dnrpipe) {
10560 dnflow->rule.info = pd->act.dnrpipe;
10561 }
10562 else if (pd->dir == dndir && pd->act.dnpipe) {
10563 dnflow->rule.info = pd->act.dnpipe;
10564 }
10565 else {
10566 return (false);
10567 }
10568
10569 dnflow->rule.info |= IPFW_IS_DUMMYNET;
10570 if (r->free_flags & PFRULE_DN_IS_PIPE || pd->act.flags & PFSTATE_DN_IS_PIPE)
10571 dnflow->rule.info |= IPFW_IS_PIPE;
10572
10573 dnflow->f_id.proto = pd->proto;
10574 dnflow->f_id.extra = dnflow->rule.info;
10575 if (s)
10576 af = s->key[PF_SK_STACK]->af;
10577
10578 switch (af) {
10579 case AF_INET:
10580 dnflow->f_id.addr_type = 4;
10581 if (s) {
10582 dnflow->f_id.src_ip = htonl(
10583 s->key[PF_SK_STACK]->addr[pd->sidx].v4.s_addr);
10584 dnflow->f_id.dst_ip = htonl(
10585 s->key[PF_SK_STACK]->addr[pd->didx].v4.s_addr);
10586 } else {
10587 dnflow->f_id.src_ip = ntohl(pd->src->v4.s_addr);
10588 dnflow->f_id.dst_ip = ntohl(pd->dst->v4.s_addr);
10589 }
10590 break;
10591 case AF_INET6:
10592 dnflow->f_id.addr_type = 6;
10593
10594 if (s) {
10595 dnflow->f_id.src_ip6 =
10596 s->key[PF_SK_STACK]->addr[pd->sidx].v6;
10597 dnflow->f_id.dst_ip6 =
10598 s->key[PF_SK_STACK]->addr[pd->didx].v6;
10599 } else {
10600 dnflow->f_id.src_ip6 = pd->src->v6;
10601 dnflow->f_id.dst_ip6 = pd->dst->v6;
10602 }
10603 break;
10604 }
10605
10606 /*
10607 * Separate this out, because while we pass the pre-NAT addresses to
10608 * dummynet we want the post-nat address family in case of nat64.
10609 * Dummynet may call ip_output/ip6_output itself, and we need it to
10610 * call the correct one.
10611 */
10612 if (pd->naf == AF_INET6)
10613 dnflow->flags |= IPFW_ARGS_IP6;
10614
10615 return (true);
10616 }
10617
10618 int
pf_test_eth(int dir,int pflags,struct ifnet * ifp,struct mbuf ** m0,struct inpcb * inp)10619 pf_test_eth(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
10620 struct inpcb *inp)
10621 {
10622 struct pfi_kkif *kif;
10623 struct mbuf *m = *m0;
10624
10625 M_ASSERTPKTHDR(m);
10626 MPASS(ifp->if_vnet == curvnet);
10627 NET_EPOCH_ASSERT();
10628
10629 if (!V_pf_status.running)
10630 return (PF_PASS);
10631
10632 kif = (struct pfi_kkif *)ifp->if_pf_kif;
10633
10634 if (kif == NULL) {
10635 DPFPRINTF(PF_DEBUG_URGENT,
10636 "%s: kif == NULL, if_xname %s", __func__, ifp->if_xname);
10637 return (PF_DROP);
10638 }
10639 if (kif->pfik_flags & PFI_IFLAG_SKIP)
10640 return (PF_PASS);
10641
10642 if (m->m_flags & M_SKIP_FIREWALL)
10643 return (PF_PASS);
10644
10645 if (__predict_false(! M_WRITABLE(*m0))) {
10646 m = *m0 = m_unshare(*m0, M_NOWAIT);
10647 if (*m0 == NULL)
10648 return (PF_DROP);
10649 }
10650
10651 /* Stateless! */
10652 return (pf_test_eth_rule(dir, kif, m0));
10653 }
10654
10655 static __inline void
pf_dummynet_flag_remove(struct mbuf * m,struct pf_mtag * pf_mtag)10656 pf_dummynet_flag_remove(struct mbuf *m, struct pf_mtag *pf_mtag)
10657 {
10658 struct m_tag *mtag;
10659
10660 pf_mtag->flags &= ~PF_MTAG_FLAG_DUMMYNET;
10661
10662 /* dummynet adds this tag, but pf does not need it,
10663 * and keeping it creates unexpected behavior,
10664 * e.g. in case of divert(4) usage right after dummynet. */
10665 mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
10666 if (mtag != NULL)
10667 m_tag_delete(m, mtag);
10668 }
10669
10670 static int
pf_dummynet(struct pf_pdesc * pd,struct pf_kstate * s,struct pf_krule * r,struct mbuf ** m0)10671 pf_dummynet(struct pf_pdesc *pd, struct pf_kstate *s,
10672 struct pf_krule *r, struct mbuf **m0)
10673 {
10674 return (pf_dummynet_route(pd, s, r, NULL, NULL, m0));
10675 }
10676
10677 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)10678 pf_dummynet_route(struct pf_pdesc *pd, struct pf_kstate *s,
10679 struct pf_krule *r, struct ifnet *ifp, const struct sockaddr *sa,
10680 struct mbuf **m0)
10681 {
10682 struct ip_fw_args dnflow;
10683
10684 NET_EPOCH_ASSERT();
10685
10686 if (pd->act.dnpipe == 0 && pd->act.dnrpipe == 0)
10687 return (0);
10688
10689 if (ip_dn_io_ptr == NULL) {
10690 m_freem(*m0);
10691 *m0 = NULL;
10692 return (ENOMEM);
10693 }
10694
10695 if (pd->pf_mtag == NULL &&
10696 ((pd->pf_mtag = pf_get_mtag(*m0)) == NULL)) {
10697 m_freem(*m0);
10698 *m0 = NULL;
10699 return (ENOMEM);
10700 }
10701
10702 if (ifp != NULL) {
10703 pd->pf_mtag->flags |= PF_MTAG_FLAG_ROUTE_TO;
10704
10705 pd->pf_mtag->if_index = ifp->if_index;
10706 pd->pf_mtag->if_idxgen = ifp->if_idxgen;
10707
10708 MPASS(sa != NULL);
10709
10710 switch (sa->sa_family) {
10711 case AF_INET:
10712 memcpy(&pd->pf_mtag->dst, sa,
10713 sizeof(struct sockaddr_in));
10714 break;
10715 case AF_INET6:
10716 memcpy(&pd->pf_mtag->dst, sa,
10717 sizeof(struct sockaddr_in6));
10718 break;
10719 }
10720 }
10721
10722 if (s != NULL && s->nat_rule != NULL &&
10723 s->nat_rule->action == PF_RDR &&
10724 (
10725 #ifdef INET
10726 (pd->af == AF_INET && IN_LOOPBACK(ntohl(pd->dst->v4.s_addr))) ||
10727 #endif /* INET */
10728 (pd->af == AF_INET6 && IN6_IS_ADDR_LOOPBACK(&pd->dst->v6)))) {
10729 /*
10730 * If we're redirecting to loopback mark this packet
10731 * as being local. Otherwise it might get dropped
10732 * if dummynet re-injects.
10733 */
10734 (*m0)->m_pkthdr.rcvif = V_loif;
10735 }
10736
10737 if (pf_pdesc_to_dnflow(pd, r, s, &dnflow)) {
10738 pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
10739 pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNETED;
10740 ip_dn_io_ptr(m0, &dnflow);
10741 if (*m0 != NULL) {
10742 pd->pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
10743 pf_dummynet_flag_remove(*m0, pd->pf_mtag);
10744 }
10745 }
10746
10747 return (0);
10748 }
10749
10750 static int
pf_walk_option(struct pf_pdesc * pd,struct ip * h,int off,int end,u_short * reason)10751 pf_walk_option(struct pf_pdesc *pd, struct ip *h, int off, int end,
10752 u_short *reason)
10753 {
10754 uint8_t type, length, opts[15 * 4 - sizeof(struct ip)];
10755
10756 /* IP header in payload of ICMP packet may be too short */
10757 if (pd->m->m_pkthdr.len < end) {
10758 DPFPRINTF(PF_DEBUG_MISC, "IP option too short");
10759 REASON_SET(reason, PFRES_SHORT);
10760 return (PF_DROP);
10761 }
10762
10763 MPASS(end - off <= sizeof(opts));
10764 m_copydata(pd->m, off, end - off, opts);
10765 end -= off;
10766 off = 0;
10767
10768 while (off < end) {
10769 type = opts[off];
10770 if (type == IPOPT_EOL)
10771 break;
10772 if (type == IPOPT_NOP) {
10773 off++;
10774 continue;
10775 }
10776 if (off + 2 > end) {
10777 DPFPRINTF(PF_DEBUG_MISC, "IP length opt");
10778 REASON_SET(reason, PFRES_IPOPTIONS);
10779 return (PF_DROP);
10780 }
10781 length = opts[off + 1];
10782 if (length < 2) {
10783 DPFPRINTF(PF_DEBUG_MISC, "IP short opt");
10784 REASON_SET(reason, PFRES_IPOPTIONS);
10785 return (PF_DROP);
10786 }
10787 if (off + length > end) {
10788 DPFPRINTF(PF_DEBUG_MISC, "IP long opt");
10789 REASON_SET(reason, PFRES_IPOPTIONS);
10790 return (PF_DROP);
10791 }
10792 switch (type) {
10793 case IPOPT_RA:
10794 pd->badopts |= PF_OPT_ROUTER_ALERT;
10795 break;
10796 default:
10797 pd->badopts |= PF_OPT_OTHER;
10798 break;
10799 }
10800 off += length;
10801 }
10802
10803 return (PF_PASS);
10804 }
10805
10806 static int
pf_walk_header(struct pf_pdesc * pd,struct ip * h,u_short * reason)10807 pf_walk_header(struct pf_pdesc *pd, struct ip *h, u_short *reason)
10808 {
10809 struct ah ext;
10810 u_int32_t hlen, end;
10811 int hdr_cnt;
10812
10813 hlen = h->ip_hl << 2;
10814 if (hlen < sizeof(struct ip) || hlen > ntohs(h->ip_len)) {
10815 REASON_SET(reason, PFRES_SHORT);
10816 return (PF_DROP);
10817 }
10818 if (hlen != sizeof(struct ip)) {
10819 if (pf_walk_option(pd, h, pd->off + sizeof(struct ip),
10820 pd->off + hlen, reason) != PF_PASS)
10821 return (PF_DROP);
10822 /* header options which contain only padding is fishy */
10823 if (pd->badopts == 0)
10824 pd->badopts |= PF_OPT_OTHER;
10825 }
10826 end = pd->off + ntohs(h->ip_len);
10827 pd->off += hlen;
10828 pd->proto = h->ip_p;
10829 /* IGMP packets have router alert options, allow them */
10830 if (pd->proto == IPPROTO_IGMP) {
10831 /*
10832 * According to RFC 1112 ttl must be set to 1 in all IGMP
10833 * packets sent to 224.0.0.1
10834 */
10835 if ((h->ip_ttl != 1) &&
10836 (h->ip_dst.s_addr == INADDR_ALLHOSTS_GROUP)) {
10837 DPFPRINTF(PF_DEBUG_MISC, "Invalid IGMP");
10838 REASON_SET(reason, PFRES_IPOPTIONS);
10839 return (PF_DROP);
10840 }
10841 pd->badopts &= ~PF_OPT_ROUTER_ALERT;
10842 }
10843 /* stop walking over non initial fragments */
10844 if ((h->ip_off & htons(IP_OFFMASK)) != 0)
10845 return (PF_PASS);
10846 for (hdr_cnt = 0; hdr_cnt < PF_HDR_LIMIT; hdr_cnt++) {
10847 switch (pd->proto) {
10848 case IPPROTO_AH:
10849 /* fragments may be short */
10850 if ((h->ip_off & htons(IP_MF | IP_OFFMASK)) != 0 &&
10851 end < pd->off + sizeof(ext))
10852 return (PF_PASS);
10853 if (!pf_pull_hdr(pd->m, pd->off, &ext, sizeof(ext),
10854 reason, AF_INET)) {
10855 DPFPRINTF(PF_DEBUG_MISC, "IP short exthdr");
10856 return (PF_DROP);
10857 }
10858 pd->off += (ext.ah_len + 2) * 4;
10859 pd->proto = ext.ah_nxt;
10860 break;
10861 default:
10862 return (PF_PASS);
10863 }
10864 }
10865 DPFPRINTF(PF_DEBUG_MISC, "IPv4 nested authentication header limit");
10866 REASON_SET(reason, PFRES_IPOPTIONS);
10867 return (PF_DROP);
10868 }
10869
10870 #ifdef INET6
10871 static int
pf_walk_option6(struct pf_pdesc * pd,struct ip6_hdr * h,int off,int end,u_short * reason)10872 pf_walk_option6(struct pf_pdesc *pd, struct ip6_hdr *h, int off, int end,
10873 u_short *reason)
10874 {
10875 struct ip6_opt opt;
10876 struct ip6_opt_jumbo jumbo;
10877
10878 while (off < end) {
10879 if (!pf_pull_hdr(pd->m, off, &opt.ip6o_type,
10880 sizeof(opt.ip6o_type), reason, AF_INET6)) {
10881 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short opt type");
10882 return (PF_DROP);
10883 }
10884 if (opt.ip6o_type == IP6OPT_PAD1) {
10885 off++;
10886 continue;
10887 }
10888 if (!pf_pull_hdr(pd->m, off, &opt, sizeof(opt),
10889 reason, AF_INET6)) {
10890 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short opt");
10891 return (PF_DROP);
10892 }
10893 if (off + sizeof(opt) + opt.ip6o_len > end) {
10894 DPFPRINTF(PF_DEBUG_MISC, "IPv6 long opt");
10895 REASON_SET(reason, PFRES_IPOPTIONS);
10896 return (PF_DROP);
10897 }
10898 switch (opt.ip6o_type) {
10899 case IP6OPT_PADN:
10900 break;
10901 case IP6OPT_JUMBO:
10902 pd->badopts |= PF_OPT_JUMBO;
10903 if (pd->jumbolen != 0) {
10904 DPFPRINTF(PF_DEBUG_MISC, "IPv6 multiple jumbo");
10905 REASON_SET(reason, PFRES_IPOPTIONS);
10906 return (PF_DROP);
10907 }
10908 if (ntohs(h->ip6_plen) != 0) {
10909 DPFPRINTF(PF_DEBUG_MISC, "IPv6 bad jumbo plen");
10910 REASON_SET(reason, PFRES_IPOPTIONS);
10911 return (PF_DROP);
10912 }
10913 if (!pf_pull_hdr(pd->m, off, &jumbo, sizeof(jumbo),
10914 reason, AF_INET6)) {
10915 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short jumbo");
10916 return (PF_DROP);
10917 }
10918 memcpy(&pd->jumbolen, jumbo.ip6oj_jumbo_len,
10919 sizeof(pd->jumbolen));
10920 pd->jumbolen = ntohl(pd->jumbolen);
10921 if (pd->jumbolen < IPV6_MAXPACKET) {
10922 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short jumbolen");
10923 REASON_SET(reason, PFRES_IPOPTIONS);
10924 return (PF_DROP);
10925 }
10926 break;
10927 case IP6OPT_ROUTER_ALERT:
10928 pd->badopts |= PF_OPT_ROUTER_ALERT;
10929 break;
10930 default:
10931 pd->badopts |= PF_OPT_OTHER;
10932 break;
10933 }
10934 off += sizeof(opt) + opt.ip6o_len;
10935 }
10936
10937 return (PF_PASS);
10938 }
10939
10940 int
pf_walk_header6(struct pf_pdesc * pd,struct ip6_hdr * h,u_short * reason)10941 pf_walk_header6(struct pf_pdesc *pd, struct ip6_hdr *h, u_short *reason)
10942 {
10943 struct ip6_frag frag;
10944 struct ip6_ext ext;
10945 struct icmp6_hdr icmp6;
10946 struct ip6_rthdr rthdr;
10947 uint32_t end;
10948 int hdr_cnt, fraghdr_cnt = 0, rthdr_cnt = 0;
10949
10950 pd->off += sizeof(struct ip6_hdr);
10951 end = pd->off + ntohs(h->ip6_plen);
10952 pd->fragoff = pd->extoff = pd->jumbolen = 0;
10953 pd->proto = h->ip6_nxt;
10954 for (hdr_cnt = 0; hdr_cnt < PF_HDR_LIMIT; hdr_cnt++) {
10955 switch (pd->proto) {
10956 case IPPROTO_ROUTING:
10957 case IPPROTO_DSTOPTS:
10958 pd->badopts |= PF_OPT_OTHER;
10959 break;
10960 case IPPROTO_HOPOPTS:
10961 if (!pf_pull_hdr(pd->m, pd->off, &ext, sizeof(ext),
10962 reason, AF_INET6)) {
10963 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short exthdr");
10964 return (PF_DROP);
10965 }
10966 if (pf_walk_option6(pd, h, pd->off + sizeof(ext),
10967 pd->off + (ext.ip6e_len + 1) * 8,
10968 reason) != PF_PASS)
10969 return (PF_DROP);
10970 /* option header which contains only padding is fishy */
10971 if (pd->badopts == 0)
10972 pd->badopts |= PF_OPT_OTHER;
10973 break;
10974 }
10975 switch (pd->proto) {
10976 case IPPROTO_FRAGMENT:
10977 if (fraghdr_cnt++) {
10978 DPFPRINTF(PF_DEBUG_MISC, "IPv6 multiple fragment");
10979 REASON_SET(reason, PFRES_FRAG);
10980 return (PF_DROP);
10981 }
10982 /* jumbo payload packets cannot be fragmented */
10983 if (pd->jumbolen != 0) {
10984 DPFPRINTF(PF_DEBUG_MISC, "IPv6 fragmented jumbo");
10985 REASON_SET(reason, PFRES_FRAG);
10986 return (PF_DROP);
10987 }
10988 if (!pf_pull_hdr(pd->m, pd->off, &frag, sizeof(frag),
10989 reason, AF_INET6)) {
10990 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short fragment");
10991 return (PF_DROP);
10992 }
10993 /* stop walking over non initial fragments */
10994 if (ntohs((frag.ip6f_offlg & IP6F_OFF_MASK)) != 0) {
10995 pd->fragoff = pd->off;
10996 return (PF_PASS);
10997 }
10998 /* RFC6946: reassemble only non atomic fragments */
10999 if (frag.ip6f_offlg & IP6F_MORE_FRAG)
11000 pd->fragoff = pd->off;
11001 pd->off += sizeof(frag);
11002 pd->proto = frag.ip6f_nxt;
11003 break;
11004 case IPPROTO_ROUTING:
11005 if (rthdr_cnt++) {
11006 DPFPRINTF(PF_DEBUG_MISC, "IPv6 multiple rthdr");
11007 REASON_SET(reason, PFRES_IPOPTIONS);
11008 return (PF_DROP);
11009 }
11010 /* fragments may be short */
11011 if (pd->fragoff != 0 && end < pd->off + sizeof(rthdr)) {
11012 pd->off = pd->fragoff;
11013 pd->proto = IPPROTO_FRAGMENT;
11014 return (PF_PASS);
11015 }
11016 if (!pf_pull_hdr(pd->m, pd->off, &rthdr, sizeof(rthdr),
11017 reason, AF_INET6)) {
11018 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short rthdr");
11019 return (PF_DROP);
11020 }
11021 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
11022 DPFPRINTF(PF_DEBUG_MISC, "IPv6 rthdr0");
11023 REASON_SET(reason, PFRES_IPOPTIONS);
11024 return (PF_DROP);
11025 }
11026 /* FALLTHROUGH */
11027 case IPPROTO_HOPOPTS:
11028 /* RFC2460 4.1: Hop-by-Hop only after IPv6 header */
11029 if (pd->proto == IPPROTO_HOPOPTS && hdr_cnt > 0) {
11030 DPFPRINTF(PF_DEBUG_MISC, "IPv6 hopopts not first");
11031 REASON_SET(reason, PFRES_IPOPTIONS);
11032 return (PF_DROP);
11033 }
11034 /* FALLTHROUGH */
11035 case IPPROTO_AH:
11036 case IPPROTO_DSTOPTS:
11037 if (!pf_pull_hdr(pd->m, pd->off, &ext, sizeof(ext),
11038 reason, AF_INET6)) {
11039 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short exthdr");
11040 return (PF_DROP);
11041 }
11042 /* fragments may be short */
11043 if (pd->fragoff != 0 && end < pd->off + sizeof(ext)) {
11044 pd->off = pd->fragoff;
11045 pd->proto = IPPROTO_FRAGMENT;
11046 return (PF_PASS);
11047 }
11048 /* reassembly needs the ext header before the frag */
11049 if (pd->fragoff == 0)
11050 pd->extoff = pd->off;
11051 if (pd->proto == IPPROTO_HOPOPTS && pd->fragoff == 0 &&
11052 ntohs(h->ip6_plen) == 0 && pd->jumbolen != 0) {
11053 DPFPRINTF(PF_DEBUG_MISC, "IPv6 missing jumbo");
11054 REASON_SET(reason, PFRES_IPOPTIONS);
11055 return (PF_DROP);
11056 }
11057 if (pd->proto == IPPROTO_AH)
11058 pd->off += (ext.ip6e_len + 2) * 4;
11059 else
11060 pd->off += (ext.ip6e_len + 1) * 8;
11061 pd->proto = ext.ip6e_nxt;
11062 break;
11063 case IPPROTO_ICMPV6:
11064 /* fragments may be short, ignore inner header then */
11065 if (pd->fragoff != 0 && end < pd->off + sizeof(icmp6)) {
11066 pd->off = pd->fragoff;
11067 pd->proto = IPPROTO_FRAGMENT;
11068 return (PF_PASS);
11069 }
11070 if (!pf_pull_hdr(pd->m, pd->off, &icmp6, sizeof(icmp6),
11071 reason, AF_INET6)) {
11072 DPFPRINTF(PF_DEBUG_MISC,
11073 "IPv6 short icmp6hdr");
11074 return (PF_DROP);
11075 }
11076 /* ICMP multicast packets have router alert options */
11077 switch (icmp6.icmp6_type) {
11078 case MLD_LISTENER_QUERY:
11079 case MLD_LISTENER_REPORT:
11080 case MLD_LISTENER_DONE:
11081 case MLDV2_LISTENER_REPORT:
11082 /*
11083 * According to RFC 2710 all MLD messages are
11084 * sent with hop-limit (ttl) set to 1, and link
11085 * local source address. If either one is
11086 * missing then MLD message is invalid and
11087 * should be discarded.
11088 */
11089 if ((h->ip6_hlim != 1) ||
11090 !IN6_IS_ADDR_LINKLOCAL(&h->ip6_src)) {
11091 DPFPRINTF(PF_DEBUG_MISC, "Invalid MLD");
11092 REASON_SET(reason, PFRES_IPOPTIONS);
11093 return (PF_DROP);
11094 }
11095 pd->badopts &= ~PF_OPT_ROUTER_ALERT;
11096 break;
11097 }
11098 return (PF_PASS);
11099 case IPPROTO_TCP:
11100 case IPPROTO_UDP:
11101 case IPPROTO_SCTP:
11102 /* fragments may be short, ignore inner header then */
11103 if (pd->fragoff != 0 && end < pd->off +
11104 (pd->proto == IPPROTO_TCP ? sizeof(struct tcphdr) :
11105 pd->proto == IPPROTO_UDP ? sizeof(struct udphdr) :
11106 pd->proto == IPPROTO_SCTP ? sizeof(struct sctphdr) :
11107 sizeof(struct icmp6_hdr))) {
11108 pd->off = pd->fragoff;
11109 pd->proto = IPPROTO_FRAGMENT;
11110 }
11111 /* FALLTHROUGH */
11112 default:
11113 return (PF_PASS);
11114 }
11115 }
11116 DPFPRINTF(PF_DEBUG_MISC, "IPv6 nested extension header limit");
11117 REASON_SET(reason, PFRES_IPOPTIONS);
11118 return (PF_DROP);
11119 }
11120 #endif /* INET6 */
11121
11122 static void
pf_init_pdesc(struct pf_pdesc * pd,struct mbuf * m)11123 pf_init_pdesc(struct pf_pdesc *pd, struct mbuf *m)
11124 {
11125 memset(pd, 0, sizeof(*pd));
11126 pd->pf_mtag = pf_find_mtag(m);
11127 pd->m = m;
11128 }
11129
11130 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)11131 pf_setup_pdesc(sa_family_t af, int dir, struct pf_pdesc *pd, struct mbuf **m0,
11132 u_short *action, u_short *reason, struct pfi_kkif *kif,
11133 struct pf_rule_actions *default_actions)
11134 {
11135 pd->dir = dir;
11136 pd->kif = kif;
11137 pd->m = *m0;
11138 pd->sidx = (dir == PF_IN) ? 0 : 1;
11139 pd->didx = (dir == PF_IN) ? 1 : 0;
11140 pd->af = pd->naf = af;
11141
11142 PF_RULES_ASSERT();
11143
11144 TAILQ_INIT(&pd->sctp_multihome_jobs);
11145 if (default_actions != NULL)
11146 memcpy(&pd->act, default_actions, sizeof(pd->act));
11147
11148 if (pd->pf_mtag && pd->pf_mtag->dnpipe) {
11149 pd->act.dnpipe = pd->pf_mtag->dnpipe;
11150 pd->act.flags = pd->pf_mtag->dnflags;
11151 }
11152
11153 switch (af) {
11154 #ifdef INET
11155 case AF_INET: {
11156 struct ip *h;
11157
11158 if (__predict_false((*m0)->m_len < sizeof(struct ip)) &&
11159 (pd->m = *m0 = m_pullup(*m0, sizeof(struct ip))) == NULL) {
11160 DPFPRINTF(PF_DEBUG_URGENT,
11161 "%s: m_len < sizeof(struct ip), pullup failed",
11162 __func__);
11163 *action = PF_DROP;
11164 REASON_SET(reason, PFRES_SHORT);
11165 return (PF_DROP);
11166 }
11167
11168 h = mtod(pd->m, struct ip *);
11169 if (pd->m->m_pkthdr.len < ntohs(h->ip_len)) {
11170 *action = PF_DROP;
11171 REASON_SET(reason, PFRES_SHORT);
11172 return (PF_DROP);
11173 }
11174
11175 if (pf_normalize_ip(reason, pd) != PF_PASS) {
11176 /* We do IP header normalization and packet reassembly here */
11177 *m0 = pd->m;
11178 *action = PF_DROP;
11179 return (PF_DROP);
11180 }
11181 *m0 = pd->m;
11182 h = mtod(pd->m, struct ip *);
11183
11184 if (pf_walk_header(pd, h, reason) != PF_PASS) {
11185 *action = PF_DROP;
11186 return (PF_DROP);
11187 }
11188
11189 pd->src = (struct pf_addr *)&h->ip_src;
11190 pd->dst = (struct pf_addr *)&h->ip_dst;
11191 pf_addrcpy(&pd->osrc, pd->src, af);
11192 pf_addrcpy(&pd->odst, pd->dst, af);
11193 pd->ip_sum = &h->ip_sum;
11194 pd->tos = h->ip_tos & ~IPTOS_ECN_MASK;
11195 pd->ttl = h->ip_ttl;
11196 pd->tot_len = ntohs(h->ip_len);
11197 pd->act.rtableid = -1;
11198 pd->df = h->ip_off & htons(IP_DF);
11199 pd->virtual_proto = (h->ip_off & htons(IP_MF | IP_OFFMASK)) ?
11200 PF_VPROTO_FRAGMENT : pd->proto;
11201
11202 break;
11203 }
11204 #endif /* INET */
11205 #ifdef INET6
11206 case AF_INET6: {
11207 struct ip6_hdr *h;
11208
11209 if (__predict_false((*m0)->m_len < sizeof(struct ip6_hdr)) &&
11210 (pd->m = *m0 = m_pullup(*m0, sizeof(struct ip6_hdr))) == NULL) {
11211 DPFPRINTF(PF_DEBUG_URGENT,
11212 "%s: m_len < sizeof(struct ip6_hdr)"
11213 ", pullup failed", __func__);
11214 *action = PF_DROP;
11215 REASON_SET(reason, PFRES_SHORT);
11216 return (PF_DROP);
11217 }
11218
11219 h = mtod(pd->m, struct ip6_hdr *);
11220 if (pd->m->m_pkthdr.len <
11221 sizeof(struct ip6_hdr) + ntohs(h->ip6_plen)) {
11222 *action = PF_DROP;
11223 REASON_SET(reason, PFRES_SHORT);
11224 return (PF_DROP);
11225 }
11226
11227 /*
11228 * we do not support jumbogram. if we keep going, zero ip6_plen
11229 * will do something bad, so drop the packet for now.
11230 */
11231 if (htons(h->ip6_plen) == 0) {
11232 *action = PF_DROP;
11233 return (PF_DROP);
11234 }
11235
11236 if (pf_walk_header6(pd, h, reason) != PF_PASS) {
11237 *action = PF_DROP;
11238 return (PF_DROP);
11239 }
11240
11241 h = mtod(pd->m, struct ip6_hdr *);
11242 pd->src = (struct pf_addr *)&h->ip6_src;
11243 pd->dst = (struct pf_addr *)&h->ip6_dst;
11244 pf_addrcpy(&pd->osrc, pd->src, af);
11245 pf_addrcpy(&pd->odst, pd->dst, af);
11246 pd->ip_sum = NULL;
11247 pd->tos = IPV6_DSCP(h);
11248 pd->ttl = h->ip6_hlim;
11249 pd->tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
11250 pd->act.rtableid = -1;
11251
11252 pd->virtual_proto = (pd->fragoff != 0) ?
11253 PF_VPROTO_FRAGMENT : pd->proto;
11254
11255 /* We do IP header normalization and packet reassembly here */
11256 if (pf_normalize_ip6(pd->fragoff, reason, pd) !=
11257 PF_PASS) {
11258 *m0 = pd->m;
11259 *action = PF_DROP;
11260 return (PF_DROP);
11261 }
11262 *m0 = pd->m;
11263 if (pd->m == NULL) {
11264 /* packet sits in reassembly queue, no error */
11265 *action = PF_PASS;
11266 return (PF_DROP);
11267 }
11268
11269 /* Update pointers into the packet. */
11270 h = mtod(pd->m, struct ip6_hdr *);
11271 pd->src = (struct pf_addr *)&h->ip6_src;
11272 pd->dst = (struct pf_addr *)&h->ip6_dst;
11273
11274 pd->off = 0;
11275
11276 if (pf_walk_header6(pd, h, reason) != PF_PASS) {
11277 *action = PF_DROP;
11278 return (PF_DROP);
11279 }
11280
11281 if (m_tag_find(pd->m, PACKET_TAG_PF_REASSEMBLED, NULL) != NULL) {
11282 /*
11283 * Reassembly may have changed the next protocol from
11284 * fragment to something else, so update.
11285 */
11286 pd->virtual_proto = pd->proto;
11287 MPASS(pd->fragoff == 0);
11288 }
11289
11290 if (pd->fragoff != 0)
11291 pd->virtual_proto = PF_VPROTO_FRAGMENT;
11292
11293 break;
11294 }
11295 #endif /* INET6 */
11296 default:
11297 panic("pf_setup_pdesc called with illegal af %u", af);
11298 }
11299
11300 switch (pd->virtual_proto) {
11301 case IPPROTO_TCP: {
11302 struct tcphdr *th = &pd->hdr.tcp;
11303
11304 if (!pf_pull_hdr(pd->m, pd->off, th, sizeof(*th),
11305 reason, af)) {
11306 *action = PF_DROP;
11307 REASON_SET(reason, PFRES_SHORT);
11308 return (PF_DROP);
11309 }
11310 pd->hdrlen = sizeof(*th);
11311 pd->p_len = pd->tot_len - pd->off - (th->th_off << 2);
11312 pd->sport = &th->th_sport;
11313 pd->dport = &th->th_dport;
11314 pd->pcksum = &th->th_sum;
11315 break;
11316 }
11317 case IPPROTO_UDP: {
11318 struct udphdr *uh = &pd->hdr.udp;
11319
11320 if (!pf_pull_hdr(pd->m, pd->off, uh, sizeof(*uh),
11321 reason, af)) {
11322 *action = PF_DROP;
11323 REASON_SET(reason, PFRES_SHORT);
11324 return (PF_DROP);
11325 }
11326 pd->hdrlen = sizeof(*uh);
11327 if (uh->uh_dport == 0 ||
11328 ntohs(uh->uh_ulen) > pd->m->m_pkthdr.len - pd->off ||
11329 ntohs(uh->uh_ulen) < sizeof(struct udphdr)) {
11330 *action = PF_DROP;
11331 REASON_SET(reason, PFRES_SHORT);
11332 return (PF_DROP);
11333 }
11334 pd->sport = &uh->uh_sport;
11335 pd->dport = &uh->uh_dport;
11336 pd->pcksum = &uh->uh_sum;
11337 break;
11338 }
11339 case IPPROTO_SCTP: {
11340 if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.sctp, sizeof(pd->hdr.sctp),
11341 reason, af)) {
11342 *action = PF_DROP;
11343 REASON_SET(reason, PFRES_SHORT);
11344 return (PF_DROP);
11345 }
11346 pd->hdrlen = sizeof(pd->hdr.sctp);
11347 pd->p_len = pd->tot_len - pd->off;
11348
11349 pd->sport = &pd->hdr.sctp.src_port;
11350 pd->dport = &pd->hdr.sctp.dest_port;
11351 if (pd->hdr.sctp.src_port == 0 || pd->hdr.sctp.dest_port == 0) {
11352 *action = PF_DROP;
11353 REASON_SET(reason, PFRES_SHORT);
11354 return (PF_DROP);
11355 }
11356
11357 /*
11358 * Placeholder. The SCTP checksum is 32-bits, but
11359 * pf_test_state() expects to update a 16-bit checksum.
11360 * Provide a dummy value which we'll subsequently ignore.
11361 * Do this before pf_scan_sctp() so any jobs we enqueue
11362 * have a pcksum set.
11363 */
11364 pd->pcksum = &pd->sctp_dummy_sum;
11365
11366 if (pf_scan_sctp(pd) != PF_PASS) {
11367 *action = PF_DROP;
11368 REASON_SET(reason, PFRES_SHORT);
11369 return (PF_DROP);
11370 }
11371 break;
11372 }
11373 case IPPROTO_ICMP: {
11374 if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp, ICMP_MINLEN,
11375 reason, af)) {
11376 *action = PF_DROP;
11377 REASON_SET(reason, PFRES_SHORT);
11378 return (PF_DROP);
11379 }
11380 pd->pcksum = &pd->hdr.icmp.icmp_cksum;
11381 pd->hdrlen = ICMP_MINLEN;
11382 break;
11383 }
11384 #ifdef INET6
11385 case IPPROTO_ICMPV6: {
11386 size_t icmp_hlen = sizeof(struct icmp6_hdr);
11387
11388 if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
11389 reason, af)) {
11390 *action = PF_DROP;
11391 REASON_SET(reason, PFRES_SHORT);
11392 return (PF_DROP);
11393 }
11394 /* ICMP headers we look further into to match state */
11395 switch (pd->hdr.icmp6.icmp6_type) {
11396 case MLD_LISTENER_QUERY:
11397 case MLD_LISTENER_REPORT:
11398 icmp_hlen = sizeof(struct mld_hdr);
11399 break;
11400 case ND_NEIGHBOR_SOLICIT:
11401 case ND_NEIGHBOR_ADVERT:
11402 icmp_hlen = sizeof(struct nd_neighbor_solicit);
11403 /* FALLTHROUGH */
11404 case ND_ROUTER_SOLICIT:
11405 case ND_ROUTER_ADVERT:
11406 case ND_REDIRECT:
11407 if (pd->ttl != 255) {
11408 *action = PF_DROP;
11409 REASON_SET(reason, PFRES_NORM);
11410 return (PF_DROP);
11411 }
11412 break;
11413 }
11414 if (icmp_hlen > sizeof(struct icmp6_hdr) &&
11415 !pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
11416 reason, af)) {
11417 *action = PF_DROP;
11418 REASON_SET(reason, PFRES_SHORT);
11419 return (PF_DROP);
11420 }
11421 pd->hdrlen = icmp_hlen;
11422 pd->pcksum = &pd->hdr.icmp6.icmp6_cksum;
11423 break;
11424 }
11425 #endif /* INET6 */
11426 default:
11427 /*
11428 * Placeholder value, so future calls to pf_change_ap() don't
11429 * try to update a NULL checksum pointer.
11430 */
11431 pd->pcksum = &pd->sctp_dummy_sum;
11432 break;
11433 }
11434
11435 if (pd->sport)
11436 pd->osport = pd->nsport = *pd->sport;
11437 if (pd->dport)
11438 pd->odport = pd->ndport = *pd->dport;
11439
11440 MPASS(pd->pcksum != NULL);
11441
11442 return (PF_PASS);
11443 }
11444
11445 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)11446 pf_rule_counters_inc(struct pf_pdesc *pd, struct pf_krule *r, int dir_out,
11447 int op_pass, sa_family_t af, struct pf_addr *src_host,
11448 struct pf_addr *dst_host)
11449 {
11450 pf_counter_u64_add_protected(&(r->packets[dir_out]), 1);
11451 pf_counter_u64_add_protected(&(r->bytes[dir_out]), pd->tot_len);
11452 pf_update_timestamp(r);
11453
11454 if (r->src.addr.type == PF_ADDR_TABLE)
11455 pfr_update_stats(r->src.addr.p.tbl, src_host, af,
11456 pd->tot_len, dir_out, op_pass, r->src.neg);
11457 if (r->dst.addr.type == PF_ADDR_TABLE)
11458 pfr_update_stats(r->dst.addr.p.tbl, dst_host, af,
11459 pd->tot_len, dir_out, op_pass, r->dst.neg);
11460 }
11461
11462 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)11463 pf_counters_inc(int action, struct pf_pdesc *pd, struct pf_kstate *s,
11464 struct pf_krule *r, struct pf_krule *a, struct pf_krule_slist *match_rules)
11465 {
11466 struct pf_krule_slist *mr = match_rules;
11467 struct pf_krule_item *ri;
11468 struct pf_krule *nr = NULL;
11469 struct pf_addr *src_host = pd->src;
11470 struct pf_addr *dst_host = pd->dst;
11471 struct pf_state_key *key;
11472 int dir_out = (pd->dir == PF_OUT);
11473 int op_r_pass = (r->action == PF_PASS);
11474 int op_pass = (action == PF_PASS || action == PF_AFRT);
11475 int s_dir_in, s_dir_out, s_dir_rev;
11476 sa_family_t af = pd->af;
11477
11478 pf_counter_u64_critical_enter();
11479
11480 /*
11481 * Set AF for interface counters, it will be later overwritten for
11482 * rule and state counters with value from proper state key.
11483 */
11484 if (action == PF_AFRT) {
11485 MPASS(s != NULL);
11486 if (s->direction == PF_OUT && dir_out)
11487 af = pd->naf;
11488 }
11489
11490 pf_counter_u64_add_protected(
11491 &pd->kif->pfik_bytes[af == AF_INET6][dir_out][!op_pass],
11492 pd->tot_len);
11493 pf_counter_u64_add_protected(
11494 &pd->kif->pfik_packets[af == AF_INET6][dir_out][!op_pass],
11495 1);
11496
11497 /* If the rule has failed to apply, don't increase its counters */
11498 if (!(op_pass || r->action == PF_DROP)) {
11499 pf_counter_u64_critical_exit();
11500 return;
11501 }
11502
11503 if (s != NULL) {
11504 PF_STATE_LOCK_ASSERT(s);
11505 mr = &(s->match_rules);
11506
11507 /*
11508 * For af-to on the inbound direction we can determine
11509 * the direction of passing packet only by checking direction
11510 * of AF translation. The af-to in "in" direction covers both
11511 * the inbound and the outbound side of state tracking,
11512 * so pd->dir is always PF_IN. We set dir_out and s_dir_rev
11513 * in a way to count packets as if the state was outbound,
11514 * because pfctl -ss shows the state with "->", as if it was
11515 * oubound.
11516 */
11517 if (action == PF_AFRT && s->direction == PF_IN) {
11518 dir_out = (pd->naf == s->rule->naf);
11519 s_dir_in = 1;
11520 s_dir_out = 0;
11521 s_dir_rev = (pd->naf == s->rule->af);
11522 } else {
11523 dir_out = (pd->dir == PF_OUT);
11524 s_dir_in = (s->direction == PF_IN);
11525 s_dir_out = (s->direction == PF_OUT);
11526 s_dir_rev = (pd->dir != s->direction);
11527 }
11528
11529 /* pd->tot_len is a problematic with af-to rules. Sure, we can
11530 * agree that it's the post-af-to packet length that was
11531 * forwarded through a state, but what about tables which match
11532 * on pre-af-to addresses? We don't have access the the original
11533 * packet length anymore.
11534 */
11535 s->packets[s_dir_rev]++;
11536 s->bytes[s_dir_rev] += pd->tot_len;
11537
11538 /*
11539 * Source nodes are accessed unlocked here. But since we are
11540 * operating with stateful tracking and the state is locked,
11541 * those SNs could not have been freed.
11542 */
11543 for (pf_sn_types_t sn_type=0; sn_type<PF_SN_MAX; sn_type++) {
11544 if (s->sns[sn_type] != NULL) {
11545 counter_u64_add(
11546 s->sns[sn_type]->packets[dir_out],
11547 1);
11548 counter_u64_add(
11549 s->sns[sn_type]->bytes[dir_out],
11550 pd->tot_len);
11551 }
11552 }
11553
11554 /* Start with pre-NAT addresses */
11555 key = s->key[(s->direction == PF_OUT)];
11556 src_host = &(key->addr[s_dir_out]);
11557 dst_host = &(key->addr[s_dir_in]);
11558 af = key->af;
11559 if (s->nat_rule) {
11560 /* Old-style NAT rules */
11561 if (s->nat_rule->action == PF_NAT ||
11562 s->nat_rule->action == PF_RDR ||
11563 s->nat_rule->action == PF_BINAT) {
11564 nr = s->nat_rule;
11565 pf_rule_counters_inc(pd, s->nat_rule, dir_out,
11566 op_r_pass, af, src_host, dst_host);
11567 /* Use post-NAT addresses from now on */
11568 key = s->key[s_dir_in];
11569 src_host = &(key->addr[s_dir_out]);
11570 dst_host = &(key->addr[s_dir_in]);
11571 af = key->af;
11572 }
11573 }
11574 }
11575
11576 SLIST_FOREACH(ri, mr, entry) {
11577 pf_rule_counters_inc(pd, ri->r, dir_out, op_r_pass, af,
11578 src_host, dst_host);
11579 if (s && s->nat_rule == ri->r) {
11580 /* Use post-NAT addresses after a match NAT rule */
11581 key = s->key[s_dir_in];
11582 src_host = &(key->addr[s_dir_out]);
11583 dst_host = &(key->addr[s_dir_in]);
11584 af = key->af;
11585 }
11586 }
11587
11588 if (a != NULL) {
11589 pf_rule_counters_inc(pd, a, dir_out, op_r_pass, af,
11590 src_host, dst_host);
11591 }
11592
11593 if (r != nr) {
11594 pf_rule_counters_inc(pd, r, dir_out, op_r_pass, af,
11595 src_host, dst_host);
11596 }
11597
11598 pf_counter_u64_critical_exit();
11599
11600 if (s == NULL) {
11601 pf_free_match_rules(mr);
11602 }
11603 }
11604
11605 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)11606 pf_log_matches(struct pf_pdesc *pd, struct pf_krule *rm,
11607 struct pf_krule *am, struct pf_kruleset *ruleset,
11608 struct pf_krule_slist *match_rules)
11609 {
11610 struct pf_krule_item *ri;
11611
11612 /* if this is the log(matches) rule, packet has been logged already */
11613 if (rm->log & PF_LOG_MATCHES)
11614 return;
11615
11616 SLIST_FOREACH(ri, match_rules, entry)
11617 if (ri->r->log & PF_LOG_MATCHES)
11618 PFLOG_PACKET(rm->action, PFRES_MATCH, rm, am,
11619 ruleset, pd, 1, ri->r);
11620 }
11621
11622 #if defined(INET) || defined(INET6)
11623 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)11624 pf_test(sa_family_t af, int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
11625 struct inpcb *inp, struct pf_rule_actions *default_actions)
11626 {
11627 struct pfi_kkif *kif;
11628 u_short action, reason = 0;
11629 struct mbuf *m;
11630 struct m_tag *mtag;
11631 struct pf_krule *a = NULL, *r = &V_pf_default_rule;
11632 struct pf_kstate *s = NULL;
11633 struct pf_kruleset *ruleset = NULL;
11634 struct pf_krule_item *ri;
11635 struct pf_krule_slist match_rules;
11636 struct pf_pdesc pd;
11637 int use_2nd_queue = 0;
11638 uint16_t tag;
11639
11640 PF_RULES_RLOCK_TRACKER;
11641 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
11642 M_ASSERTPKTHDR(*m0);
11643 NET_EPOCH_ASSERT();
11644
11645 if (!V_pf_status.running)
11646 return (PF_PASS);
11647
11648 kif = (struct pfi_kkif *)ifp->if_pf_kif;
11649
11650 if (__predict_false(kif == NULL)) {
11651 DPFPRINTF(PF_DEBUG_URGENT,
11652 "%s: kif == NULL, if_xname %s",
11653 __func__, ifp->if_xname);
11654 return (PF_DROP);
11655 }
11656 if (kif->pfik_flags & PFI_IFLAG_SKIP) {
11657 return (PF_PASS);
11658 }
11659
11660 if ((*m0)->m_flags & M_SKIP_FIREWALL) {
11661 return (PF_PASS);
11662 }
11663
11664 if (__predict_false(! M_WRITABLE(*m0))) {
11665 /* Need to convert unmapped mbufs before calling m_unshare(). */
11666 if (mb_unmapped_to_ext(*m0, &m) != 0) {
11667 *m0 = NULL;
11668 return (PF_DROP);
11669 }
11670 MPASS(*m0 == m);
11671 *m0 = m_unshare(*m0, M_NOWAIT);
11672 if (*m0 == NULL) {
11673 return (PF_DROP);
11674 }
11675 }
11676
11677 pf_init_pdesc(&pd, *m0);
11678 SLIST_INIT(&match_rules);
11679
11680 if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_MTAG_FLAG_ROUTE_TO)) {
11681 pd.pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
11682
11683 ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
11684 pd.pf_mtag->if_idxgen);
11685 if (ifp == NULL || ifp->if_flags & IFF_DYING) {
11686 m_freem(*m0);
11687 *m0 = NULL;
11688 return (PF_PASS);
11689 }
11690
11691 /*
11692 * No need to call mb_unmapped_to_ext() here because it had
11693 * already been called in pf_route()/pf_route6() and dummynet
11694 * re-injected this packet.
11695 */
11696
11697 M_ASSERTMAPPED(*m0);
11698 (ifp->if_output)(ifp, *m0, sintosa(&pd.pf_mtag->dst), NULL);
11699 *m0 = NULL;
11700 return (PF_PASS);
11701 }
11702
11703 if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
11704 pd.pf_mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
11705 /* Dummynet re-injects packets after they've
11706 * completed their delay. We've already
11707 * processed them, so pass unconditionally. */
11708
11709 /* But only once. We may see the packet multiple times (e.g.
11710 * PFIL_IN/PFIL_OUT). */
11711 pf_dummynet_flag_remove(pd.m, pd.pf_mtag);
11712
11713 return (PF_PASS);
11714 }
11715
11716 PF_RULES_RLOCK();
11717
11718 if (pf_setup_pdesc(af, dir, &pd, m0, &action, &reason,
11719 kif, default_actions) != PF_PASS) {
11720 if (action != PF_PASS)
11721 pd.act.log |= PF_LOG_FORCE;
11722 goto done;
11723 }
11724
11725 #ifdef INET
11726 if (af == AF_INET && dir == PF_OUT && pflags & PFIL_FWD &&
11727 pd.df && (*m0)->m_pkthdr.len > ifp->if_mtu) {
11728 PF_RULES_RUNLOCK();
11729 icmp_error(*m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG,
11730 0, ifp->if_mtu);
11731 *m0 = NULL;
11732 return (PF_DROP);
11733 }
11734 #endif /* INET */
11735 #ifdef INET6
11736 /*
11737 * If we end up changing IP addresses (e.g. binat) the stack may get
11738 * confused and fail to send the icmp6 packet too big error. Just send
11739 * it here, before we do any NAT.
11740 */
11741 if (af == AF_INET6 && dir == PF_OUT && pflags & PFIL_FWD &&
11742 in6_ifmtu(ifp) < pf_max_frag_size(*m0)) {
11743 PF_RULES_RUNLOCK();
11744 icmp6_error(*m0, ICMP6_PACKET_TOO_BIG, 0, in6_ifmtu(ifp));
11745 *m0 = NULL;
11746 return (PF_DROP);
11747 }
11748 #endif /* INET6 */
11749
11750 if (__predict_false(ip_divert_ptr != NULL) &&
11751 ((mtag = m_tag_locate(pd.m, MTAG_PF_DIVERT, 0, NULL)) != NULL)) {
11752 struct pf_divert_mtag *dt = (struct pf_divert_mtag *)(mtag+1);
11753 if ((dt->idir == PF_DIVERT_MTAG_DIR_IN && dir == PF_IN) ||
11754 (dt->idir == PF_DIVERT_MTAG_DIR_OUT && dir == PF_OUT)) {
11755 if (pd.pf_mtag == NULL &&
11756 ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
11757 action = PF_DROP;
11758 goto done;
11759 }
11760 pd.pf_mtag->flags |= PF_MTAG_FLAG_PACKET_LOOPED;
11761 }
11762 if (pd.pf_mtag && pd.pf_mtag->flags & PF_MTAG_FLAG_FASTFWD_OURS_PRESENT) {
11763 pd.m->m_flags |= M_FASTFWD_OURS;
11764 pd.pf_mtag->flags &= ~PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
11765 }
11766 m_tag_delete(pd.m, mtag);
11767
11768 mtag = m_tag_locate(pd.m, MTAG_IPFW_RULE, 0, NULL);
11769 if (mtag != NULL)
11770 m_tag_delete(pd.m, mtag);
11771 }
11772
11773 switch (pd.virtual_proto) {
11774 case PF_VPROTO_FRAGMENT:
11775 /*
11776 * handle fragments that aren't reassembled by
11777 * normalization
11778 */
11779 if (kif == NULL || r == NULL) /* pflog */
11780 action = PF_DROP;
11781 else
11782 action = pf_test_rule(&r, &s, &pd, &a,
11783 &ruleset, &reason, inp, &match_rules);
11784 if (action != PF_PASS)
11785 REASON_SET(&reason, PFRES_FRAG);
11786 break;
11787
11788 case IPPROTO_TCP: {
11789 /* Respond to SYN with a syncookie. */
11790 if ((tcp_get_flags(&pd.hdr.tcp) & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
11791 pd.dir == PF_IN && pf_synflood_check(&pd)) {
11792 pf_syncookie_send(&pd, &reason);
11793 action = PF_DROP;
11794 break;
11795 }
11796
11797 if ((tcp_get_flags(&pd.hdr.tcp) & TH_ACK) && pd.p_len == 0)
11798 use_2nd_queue = 1;
11799 action = pf_normalize_tcp(&pd);
11800 if (action == PF_DROP)
11801 break;
11802 action = pf_test_state(&s, &pd, &reason);
11803 if (action == PF_PASS || action == PF_AFRT) {
11804 if (s != NULL) {
11805 if (V_pfsync_update_state_ptr != NULL)
11806 V_pfsync_update_state_ptr(s);
11807 r = s->rule;
11808 a = s->anchor;
11809 }
11810 } else if (s == NULL) {
11811 /* Validate remote SYN|ACK, re-create original SYN if
11812 * valid. */
11813 if ((tcp_get_flags(&pd.hdr.tcp) & (TH_SYN|TH_ACK|TH_RST)) ==
11814 TH_ACK && pf_syncookie_validate(&pd) &&
11815 pd.dir == PF_IN) {
11816 struct mbuf *msyn;
11817
11818 msyn = pf_syncookie_recreate_syn(&pd, &reason);
11819 if (msyn == NULL) {
11820 action = PF_DROP;
11821 break;
11822 }
11823
11824 action = pf_test(af, dir, pflags, ifp, &msyn, inp,
11825 &pd.act);
11826 m_freem(msyn);
11827 if (action != PF_PASS)
11828 break;
11829
11830 action = pf_test_state(&s, &pd, &reason);
11831 if (action != PF_PASS || s == NULL) {
11832 action = PF_DROP;
11833 break;
11834 }
11835
11836 s->src.seqhi = ntohl(pd.hdr.tcp.th_ack) - 1;
11837 s->src.seqlo = ntohl(pd.hdr.tcp.th_seq) - 1;
11838 pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_DST);
11839 action = pf_synproxy(&pd, s, &reason);
11840 break;
11841 } else {
11842 action = pf_test_rule(&r, &s, &pd,
11843 &a, &ruleset, &reason, inp, &match_rules);
11844 }
11845 }
11846 break;
11847 }
11848
11849 case IPPROTO_SCTP:
11850 action = pf_normalize_sctp(&pd);
11851 if (action == PF_DROP)
11852 break;
11853 /* fallthrough */
11854 case IPPROTO_UDP:
11855 default:
11856 action = pf_test_state(&s, &pd, &reason);
11857 if (action == PF_PASS || action == PF_AFRT) {
11858 if (s != NULL) {
11859 if (V_pfsync_update_state_ptr != NULL)
11860 V_pfsync_update_state_ptr(s);
11861 r = s->rule;
11862 a = s->anchor;
11863 }
11864 } else if (s == NULL) {
11865 action = pf_test_rule(&r, &s,
11866 &pd, &a, &ruleset, &reason, inp, &match_rules);
11867 }
11868 break;
11869
11870 case IPPROTO_ICMP:
11871 case IPPROTO_ICMPV6: {
11872 if (pd.virtual_proto == IPPROTO_ICMP && af != AF_INET) {
11873 action = PF_DROP;
11874 REASON_SET(&reason, PFRES_NORM);
11875 DPFPRINTF(PF_DEBUG_MISC,
11876 "dropping IPv6 packet with ICMPv4 payload");
11877 break;
11878 }
11879 if (pd.virtual_proto == IPPROTO_ICMPV6 && af != AF_INET6) {
11880 action = PF_DROP;
11881 REASON_SET(&reason, PFRES_NORM);
11882 DPFPRINTF(PF_DEBUG_MISC,
11883 "pf: dropping IPv4 packet with ICMPv6 payload");
11884 break;
11885 }
11886 action = pf_test_state_icmp(&s, &pd, &reason);
11887 if (action == PF_PASS || action == PF_AFRT) {
11888 if (s != NULL) {
11889 if (V_pfsync_update_state_ptr != NULL)
11890 V_pfsync_update_state_ptr(s);
11891 r = s->rule;
11892 a = s->anchor;
11893 }
11894 } else if (s == NULL)
11895 action = pf_test_rule(&r, &s, &pd,
11896 &a, &ruleset, &reason, inp, &match_rules);
11897 break;
11898 }
11899
11900 }
11901
11902 done:
11903 PF_RULES_RUNLOCK();
11904
11905 /* if packet sits in reassembly queue, return without error */
11906 if (pd.m == NULL) {
11907 pf_free_match_rules(&match_rules);
11908 goto eat_pkt;
11909 }
11910
11911 if (s)
11912 memcpy(&pd.act, &s->act, sizeof(s->act));
11913
11914 if (action == PF_PASS && pd.badopts != 0 && !pd.act.allow_opts) {
11915 action = PF_DROP;
11916 REASON_SET(&reason, PFRES_IPOPTIONS);
11917 pd.act.log = PF_LOG_FORCE;
11918 DPFPRINTF(PF_DEBUG_MISC,
11919 "pf: dropping packet with dangerous headers");
11920 }
11921
11922 if (pd.act.max_pkt_size && pd.act.max_pkt_size &&
11923 pd.tot_len > pd.act.max_pkt_size) {
11924 action = PF_DROP;
11925 REASON_SET(&reason, PFRES_NORM);
11926 pd.act.log = PF_LOG_FORCE;
11927 DPFPRINTF(PF_DEBUG_MISC,
11928 "pf: dropping overly long packet");
11929 }
11930
11931 if (s) {
11932 uint8_t log = pd.act.log;
11933 memcpy(&pd.act, &s->act, sizeof(struct pf_rule_actions));
11934 pd.act.log |= log;
11935 tag = s->tag;
11936 } else {
11937 tag = r->tag;
11938 }
11939
11940 if (tag > 0 && pf_tag_packet(&pd, tag)) {
11941 action = PF_DROP;
11942 REASON_SET(&reason, PFRES_MEMORY);
11943 }
11944
11945 pf_scrub(&pd);
11946 if (pd.proto == IPPROTO_TCP && pd.act.max_mss)
11947 pf_normalize_mss(&pd);
11948
11949 if (pd.act.rtableid >= 0)
11950 M_SETFIB(pd.m, pd.act.rtableid);
11951
11952 if (pd.act.flags & PFSTATE_SETPRIO) {
11953 if (pd.tos & IPTOS_LOWDELAY)
11954 use_2nd_queue = 1;
11955 if (vlan_set_pcp(pd.m, pd.act.set_prio[use_2nd_queue])) {
11956 action = PF_DROP;
11957 REASON_SET(&reason, PFRES_MEMORY);
11958 pd.act.log = PF_LOG_FORCE;
11959 DPFPRINTF(PF_DEBUG_MISC,
11960 "pf: failed to allocate 802.1q mtag");
11961 }
11962 }
11963
11964 #ifdef ALTQ
11965 if (action == PF_PASS && pd.act.qid) {
11966 if (pd.pf_mtag == NULL &&
11967 ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
11968 action = PF_DROP;
11969 REASON_SET(&reason, PFRES_MEMORY);
11970 } else {
11971 if (s != NULL)
11972 pd.pf_mtag->qid_hash = pf_state_hash(s);
11973 if (use_2nd_queue || (pd.tos & IPTOS_LOWDELAY))
11974 pd.pf_mtag->qid = pd.act.pqid;
11975 else
11976 pd.pf_mtag->qid = pd.act.qid;
11977 /* Add hints for ecn. */
11978 pd.pf_mtag->hdr = mtod(pd.m, void *);
11979 }
11980 }
11981 #endif /* ALTQ */
11982
11983 /*
11984 * connections redirected to loopback should not match sockets
11985 * bound specifically to loopback due to security implications,
11986 * see tcp_input() and in_pcblookup_listen().
11987 */
11988 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
11989 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule != NULL &&
11990 (s->nat_rule->action == PF_RDR ||
11991 s->nat_rule->action == PF_BINAT) &&
11992 pf_is_loopback(af, pd.dst))
11993 pd.m->m_flags |= M_SKIP_FIREWALL;
11994
11995 if (action == PF_PASS && r->divert.port && !PACKET_LOOPED(&pd)) {
11996 mtag = m_tag_alloc(MTAG_PF_DIVERT, 0,
11997 sizeof(struct pf_divert_mtag), M_NOWAIT | M_ZERO);
11998 if (__predict_true(mtag != NULL && ip_divert_ptr != NULL)) {
11999 ((struct pf_divert_mtag *)(mtag+1))->port =
12000 ntohs(r->divert.port);
12001 ((struct pf_divert_mtag *)(mtag+1))->idir =
12002 (dir == PF_IN) ? PF_DIVERT_MTAG_DIR_IN :
12003 PF_DIVERT_MTAG_DIR_OUT;
12004
12005 pf_counters_inc(action, &pd, s, r, a, &match_rules);
12006
12007 if (s)
12008 PF_STATE_UNLOCK(s);
12009
12010 m_tag_prepend(pd.m, mtag);
12011 if (pd.m->m_flags & M_FASTFWD_OURS) {
12012 if (pd.pf_mtag == NULL &&
12013 ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
12014 action = PF_DROP;
12015 REASON_SET(&reason, PFRES_MEMORY);
12016 pd.act.log = PF_LOG_FORCE;
12017 DPFPRINTF(PF_DEBUG_MISC,
12018 "pf: failed to allocate tag");
12019 } else {
12020 pd.pf_mtag->flags |=
12021 PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
12022 pd.m->m_flags &= ~M_FASTFWD_OURS;
12023 }
12024 }
12025 ip_divert_ptr(*m0, s != NULL ? s->id : 0, dir == PF_IN);
12026 *m0 = NULL;
12027 return (action);
12028 } else if (mtag == NULL) {
12029 /* XXX: ipfw has the same behaviour! */
12030 action = PF_DROP;
12031 REASON_SET(&reason, PFRES_MEMORY);
12032 pd.act.log = PF_LOG_FORCE;
12033 DPFPRINTF(PF_DEBUG_MISC,
12034 "pf: failed to allocate divert tag");
12035 } else {
12036 action = PF_DROP;
12037 REASON_SET(&reason, PFRES_MATCH);
12038 pd.act.log = PF_LOG_FORCE;
12039 DPFPRINTF(PF_DEBUG_MISC,
12040 "pf: divert(4) is not loaded");
12041 }
12042 }
12043
12044 /* this flag will need revising if the pkt is forwarded */
12045 if (pd.pf_mtag)
12046 pd.pf_mtag->flags &= ~PF_MTAG_FLAG_PACKET_LOOPED;
12047
12048 if (pd.act.log) {
12049 struct pf_krule *lr;
12050
12051 if (s != NULL && s->nat_rule != NULL &&
12052 s->nat_rule->log & PF_LOG_ALL)
12053 lr = s->nat_rule;
12054 else
12055 lr = r;
12056
12057 if (pd.act.log & PF_LOG_FORCE || lr->log & PF_LOG_ALL)
12058 PFLOG_PACKET(action, reason, lr, a,
12059 ruleset, &pd, (s == NULL), NULL);
12060 if (s) {
12061 SLIST_FOREACH(ri, &s->match_rules, entry)
12062 if (ri->r->log & PF_LOG_ALL)
12063 PFLOG_PACKET(action,
12064 reason, ri->r, a, ruleset, &pd, 0, NULL);
12065 }
12066 }
12067
12068 pf_counters_inc(action, &pd, s, r, a, &match_rules);
12069
12070 switch (action) {
12071 case PF_SYNPROXY_DROP:
12072 m_freem(*m0);
12073 case PF_DEFER:
12074 *m0 = NULL;
12075 action = PF_PASS;
12076 break;
12077 case PF_DROP:
12078 m_freem(*m0);
12079 *m0 = NULL;
12080 break;
12081 case PF_AFRT:
12082 if (pf_translate_af(&pd, r)) {
12083 *m0 = pd.m;
12084 action = PF_DROP;
12085 break;
12086 }
12087 #ifdef INET
12088 if (pd.naf == AF_INET) {
12089 action = pf_route(r, kif->pfik_ifp, s, &pd,
12090 inp);
12091 }
12092 #endif /* INET */
12093 #ifdef INET6
12094 if (pd.naf == AF_INET6) {
12095 action = pf_route6(r, kif->pfik_ifp, s, &pd,
12096 inp);
12097 }
12098 #endif /* INET6 */
12099 *m0 = pd.m;
12100 goto out;
12101 break;
12102 default:
12103 if (pd.act.rt) {
12104 switch (af) {
12105 #ifdef INET
12106 case AF_INET:
12107 /* pf_route() returns unlocked. */
12108 action = pf_route(r, kif->pfik_ifp, s, &pd,
12109 inp);
12110 break;
12111 #endif /* INET */
12112 #ifdef INET6
12113 case AF_INET6:
12114 /* pf_route6() returns unlocked. */
12115 action = pf_route6(r, kif->pfik_ifp, s, &pd,
12116 inp);
12117 break;
12118 #endif /* INET6 */
12119 }
12120 *m0 = pd.m;
12121 goto out;
12122 }
12123 if (pf_dummynet(&pd, s, r, m0) != 0) {
12124 action = PF_DROP;
12125 REASON_SET(&reason, PFRES_MEMORY);
12126 }
12127 break;
12128 }
12129
12130 eat_pkt:
12131 SDT_PROBE4(pf, ip, test, done, action, reason, r, s);
12132
12133 if (s && action != PF_DROP) {
12134 if (!s->if_index_in && dir == PF_IN)
12135 s->if_index_in = ifp->if_index;
12136 else if (!s->if_index_out && dir == PF_OUT)
12137 s->if_index_out = ifp->if_index;
12138 }
12139
12140 if (s)
12141 PF_STATE_UNLOCK(s);
12142
12143 out:
12144 #ifdef INET6
12145 /* If reassembled packet passed, create new fragments. */
12146 if (af == AF_INET6 && action == PF_PASS && *m0 && dir == PF_OUT &&
12147 (! (pflags & PF_PFIL_NOREFRAGMENT)) &&
12148 (mtag = m_tag_find(pd.m, PACKET_TAG_PF_REASSEMBLED, NULL)) != NULL)
12149 action = pf_refragment6(ifp, m0, mtag, NULL, pflags & PFIL_FWD);
12150 #endif /* INET6 */
12151
12152 pf_sctp_multihome_delayed(&pd, kif, s, action);
12153
12154 return (action);
12155 }
12156 #endif /* INET || INET6 */
12157