asmap.cpp raw

   1  // Copyright (c) 2020-present The Bitcoin Core developers
   2  // Distributed under the MIT software license, see the accompanying
   3  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   4  
   5  #include <netaddress.h>
   6  #include <netgroup.h>
   7  #include <test/fuzz/fuzz.h>
   8  #include <util/asmap.h>
   9  #include <util/strencodings.h>
  10  
  11  #include <cstdint>
  12  #include <vector>
  13  
  14  using namespace util::hex_literals;
  15  
  16  //! asmap code that consumes nothing
  17  static const std::vector<std::byte> IPV6_PREFIX_ASMAP = {};
  18  
  19  //! asmap code that consumes the 96 prefix bits of ::ffff:0/96 (IPv4-in-IPv6 map)
  20  static const auto IPV4_PREFIX_ASMAP = "fb03ec0fb03fc0fe00fb03ec0fb03fc0fe00fb03ec0fb0fffffeff"_hex_v;
  21  
  22  FUZZ_TARGET(asmap)
  23  {
  24      // Encoding: [7 bits: asmap size] [1 bit: ipv6?] [3-130 bytes: asmap] [4 or 16 bytes: addr]
  25      if (buffer.size() < 1 + 3 + 4) return;
  26      int asmap_size = 3 + (buffer[0] & 127);
  27      bool ipv6 = buffer[0] & 128;
  28      const size_t addr_size = ipv6 ? ADDR_IPV6_SIZE : ADDR_IPV4_SIZE;
  29      if (buffer.size() < size_t(1 + asmap_size + addr_size)) return;
  30      std::vector<std::byte> asmap = ipv6 ? IPV6_PREFIX_ASMAP : IPV4_PREFIX_ASMAP;
  31      std::ranges::copy(std::as_bytes(buffer.subspan(1, asmap_size)), std::back_inserter(asmap));
  32      if (!CheckStandardAsmap(asmap)) return;
  33  
  34      const uint8_t* addr_data = buffer.data() + 1 + asmap_size;
  35      CNetAddr net_addr;
  36      if (ipv6) {
  37          assert(addr_size == ADDR_IPV6_SIZE);
  38          net_addr.SetLegacyIPv6({addr_data, addr_size});
  39      } else {
  40          assert(addr_size == ADDR_IPV4_SIZE);
  41          in_addr ipv4;
  42          memcpy(&ipv4, addr_data, addr_size);
  43          net_addr.SetIP(CNetAddr{ipv4});
  44      }
  45      auto netgroupman{NetGroupManager::WithEmbeddedAsmap(asmap)};
  46      (void)netgroupman.GetMappedAS(net_addr);
  47  }
  48