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