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