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