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