Repository: bitcoin/bitcoin
File: src/test/fuzz/connman.cpp (C++)

Code before:
// Copyright (c) 2020-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <addrman.h>
#include <chainparams.h>
#include <common/args.h>
#include <net.h>
#include <netaddress.h>
#include <protocol.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <test/fuzz/util/net.h>
#include <test/util/setup_common.h>
#include <util/translation.h>

#include <cstdint>
#include <vector>

namespace {
const TestingSetup* g_setup;

int32_t GetCheckRatio()
{
    return std::clamp<int32_t>(g_setup->m_node.args->GetIntArg("-checkaddrman", 0), 0, 1000000);
}

} // namespace

void initialize_connman()
{
    static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
    g_setup = testing_setup.get();
}

FUZZ_TARGET(connman, .init = initialize_connman)
{
    SeedRandomStateForTest(SeedRand::ZEROS);
    FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
    SetMockTime(ConsumeTime(fuzzed_data_provider));
    auto netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)};
    auto addr_man_ptr{std::make_unique<AddrManDeterministic>(netgroupman, fuzzed_data_provider, GetCheckRatio())};
    if (fuzzed_data_provider.ConsumeBool()) {
        const std::vector<uint8_t> serialized_data{ConsumeRandomLengthByteVector(fuzzed_data_provider)};
        DataStream ds{serialized_data};
        try {
            ds >> *addr_man_ptr;
        } catch (const std::ios_base::failure&) {
            addr_man_ptr = std::make_unique<AddrManDeterministic>(netgroupman, fuzzed_data_provider, GetCheckRatio());
        }
    }
    AddrManDeterministic& addr_man{*addr_man_ptr};
    ConnmanTestMsg connman{fuzzed_data_provider.ConsumeIntegral<uint64_t>(),
                     fuzzed_data_provider.ConsumeIntegral<uint64_t>(),
                     addr_man,
                     netgroupman,
                     Params(),
                     fuzzed_data_provider.ConsumeBool()};

    const uint64_t max_outbound_limit{fuzzed_data_provider.ConsumeIntegral<uint64_t>()};
    CConnman::Options options;
    options.nMaxOutboundLimit = max_outbound_limit;
    connman.Init(options);

    CNetAddr random_netaddr;
    CNode random_node = ConsumeNode(fuzzed_data_provider);
    CSubNet random_subnet;
    std::string random_string;

    LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100) {
        CNode& p2p_node{*ConsumeNodeAsUniquePtr(fuzzed_data_provider).release()};
        connman.AddTestNode(p2p_node);
    }

    LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) {
        CallOneOf(
            fuzzed_data_provider,
            [&] {
                random_netaddr = ConsumeNetAddr(fuzzed_data_provider);
            },
            [&] {
                random_subnet = ConsumeSubNet(fuzzed_data_provider);
            },
            [&] {
                random_string = fuzzed_data_provider.ConsumeRandomLengthString(64);
            },
            [&] {
                connman.AddNode({random_string, fuzzed_data_provider.ConsumeBool()});
            },
            [&] {
                connman.CheckIncomingNonce(fuzzed_data_provider.ConsumeIntegral<uint64_t>());
            },
            [&] {
                connman.DisconnectNode(fuzzed_data_provider.ConsumeIntegral<NodeId>());
            },
            [&] {
                connman.DisconnectNode(random_netaddr);
            },
            [&] {
                connman.DisconnectNode(random_string);
            },
            [&] {
                connman.DisconnectNode(random_subnet);
            },
            [&] {
                connman.ForEachNode([](auto) {});
            },
            [&] {
                (void)connman.ForNode(fuzzed_data_provider.ConsumeIntegral<NodeId>(), [&](auto) { return fuzzed_data_provider.ConsumeBool(); });
            },
            [&] {
                auto max_addresses = fuzzed_data_provider.ConsumeIntegral<size_t>();
                auto max_pct = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 100);
                auto filtered = fuzzed_data_provider.ConsumeBool();
                (void)connman.GetAddresses(max_addresses, max_pct, /*network=*/std::nullopt, filtered);
            },
            [&] {
                auto max_addresses = fuzzed_data_provider.ConsumeIntegral<size_t>();
                auto max_pct = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 100);
                (void)connman.GetAddresses(/*requestor=*/random_node, max_addresses, max_pct);
            },
            [&] {
                (void)connman.GetDeterministicRandomizer(fuzzed_data_provider.ConsumeIntegral<uint64_t>());
            },
            [&] {
                (void)connman.GetNodeCount(fuzzed_data_provider.PickValueInArray({ConnectionDirection::None, ConnectionDirection::In, ConnectionDirection::Out, ConnectionDirection::Both}));
            },
            [&] {
                (void)connman.OutboundTargetReached(fuzzed_data_provider.ConsumeBool());
            },
            [&] {
                CSerializedNetMsg serialized_net_msg;
                serialized_net_msg.m_type = fuzzed_data_provider.ConsumeRandomLengthString(CMessageHeader::MESSAGE_TYPE_SIZE);
                serialized_net_msg.data = ConsumeRandomLengthByteVector(fuzzed_data_provider);
                connman.PushMessage(&random_node, std::move(serialized_net_msg));
            },
            [&] {
                connman.RemoveAddedNode(random_string);
            },
            [&] {
                connman.SetNetworkActive(fuzzed_data_provider.ConsumeBool());
            },
            [&] {
                connman.SetTryNewOutboundPeer(fuzzed_data_provider.ConsumeBool());
            });
    }
    (void)connman.GetAddedNodeInfo(fuzzed_data_provider.ConsumeBool());
    (void)connman.GetExtraFullOutboundCount();
    (void)connman.GetLocalServices();
    assert(connman.GetMaxOutboundTarget() == max_outbound_limit);
    (void)connman.GetMaxOutboundTimeframe();
    (void)connman.GetMaxOutboundTimeLeftInCycle();
    (void)connman.GetNetworkActive();
    std::vector<CNodeStats> stats;
    connman.GetNodeStats(stats);
    (void)connman.GetOutboundTargetBytesLeft();
    (void)connman.GetTotalBytesRecv();
    (void)connman.GetTotalBytesSent();
    (void)connman.GetTryNewOutboundPeer();
    (void)connman.GetUseAddrmanOutgoing();
    (void)connman.ASMapHealthCheck();

    connman.ClearTestNodes();
}


Review comment (bug):
```
# echo 'XGFkZAAAAGRkZWXuXP/fcGcqb2hlcirYfg9D/uXc5eXcRZJ55eXl5eXl5eXlIiL19QAFABD3XERc
AVxhYQcAAADl5f//5eVhYWHl5eX//+Xl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl
5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eX/Km8xMTQyMjgxMUMKYWFhYWFhYQAAAAAA
YWFhYWFhYWFhYWFhYWFhe2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh8mWkovx0AAAA
AAAAAGFhYWFhYWFhYWFhgKoL//v/Kv/////l5eXl5f//ZGRy5eX//2Ry5eX///9kZHLl5f//ZHLl
5f//5eXl5eXl5eXl5Wfl//9kZHLl5f//ZHLl5f///2RkcuXl//9kcuXl//8=' | base64 --decode > ./crash_cm_1cfcffc33a

# UBSAN_OPTIONS="suppressions=$(pwd)/test/sanitizer_suppressions/ubsan:print_stacktrace=1:halt_on_error=1:report_error_type=1" FUZZ=connman ./bld/bin/fuzz -runs=1  ./crash_cm_1cfcffc33a 
INFO: Running with entropic power schedule (0xFF, 100).
INFO: Seed: 2899209193
INFO: Loaded 1 modules   (597578 inline 8-bit counters): 597578 [0x62ee33b00588, 0x62ee33b923d2), 
INFO: Loaded 1 PC tables (597578 PCs): 597578 [0x62ee33b923d8,0x62ee344b0878), 
./bld/bin/fuzz: Running 1 inputs 1 time(s) each.
Running: ./crash_cm_1cfcffc33a
./src/test/fuzz/util/net.cpp:337:43: runtime error: null pointer passed as argument 2, which is declared to never be null


Code after:
                    /*sock=*/CreateSock(AF_INET, SOCK_STREAM, IPPROTO_TCP),
                    /*permissions=*/ConsumeWeakEnum(fuzzed_data_provider, ALL_NET_PERMISSION_FLAGS),
                    /*addr_bind=*/ConsumeAddress(fuzzed_data_provider),
                    /*addr_peer=*/peer);
            },
            [&] {
                CConnman::Options options;

                options.vBinds = ConsumeServiceVector(fuzzed_data_provider);

                options.vWhiteBinds = std::vector<NetWhitebindPermissions>{
                    fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 5)};
                for (auto& wb : options.vWhiteBinds) {
                    wb.m_flags = ConsumeWeakEnum(fuzzed_data_provider, ALL_NET_PERMISSION_FLAGS);
                    wb.m_service = ConsumeService(fuzzed_data_provider);
                }

                options.onion_binds = ConsumeServiceVector(fuzzed_data_provider);

                options.bind_on_any = options.vBinds.empty() && options.vWhiteBinds.empty() &&
                                      options.onion_binds.empty();

                connman.InitBindsPublic(options);
            },
            [&] {
                connman.SocketHandlerPublic();
            });
    }
    (void)connman.GetAddedNodeInfo(fuzzed_data_provider.ConsumeBool());
    (void)connman.GetExtraFullOutboundCount();
    (void)connman.GetLocalServices();
    assert(connman.GetMaxOutboundTarget() == max_outbound_limit);
    (void)connman.GetMaxOutboundTimeframe();
    (void)connman.GetMaxOutboundTimeLeftInCycle();
    (void)connman.GetNetworkActive();
    std::vector<CNodeStats> stats;
    connman.GetNodeStats(stats);
    (void)connman.GetOutboundTargetBytesLeft();
    (void)connman.GetTotalBytesRecv();
    (void)connman.GetTotalBytesSent();
    (void)connman.GetTryNewOutboundPeer();
    (void)connman.GetUseAddrmanOutgoing();
    (void)connman.ASMapHealthCheck();

    connman.ClearTestNodes();
    g_dns_lookup = g_dns_lookup_orig;
    CreateSock = CreateSockOrig;
}