Bitcoin Core 28.0.0
P2P Digital Currency
Loading...
Searching...
No Matches
denialofservice_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-2022 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// Unit tests for denial-of-service detection/prevention code
6
7#include <banman.h>
8#include <chainparams.h>
9#include <common/args.h>
10#include <net.h>
11#include <net_processing.h>
12#include <pubkey.h>
13#include <script/sign.h>
15#include <serialize.h>
16#include <test/util/net.h>
17#include <test/util/random.h>
19#include <util/string.h>
20#include <util/time.h>
21#include <validation.h>
22
23#include <array>
24#include <stdint.h>
25
26#include <boost/test/unit_test.hpp>
27
28static CService ip(uint32_t i)
29{
30 struct in_addr s;
31 s.s_addr = i;
32 return CService(CNetAddr(s), Params().GetDefaultPort());
33}
34
35BOOST_FIXTURE_TEST_SUITE(denialofservice_tests, TestingSetup)
36
37// Test eviction of an outbound peer whose chain never advances
38// Mock a node connection, and use mocktime to simulate a peer
39// which never sends any headers messages. PeerLogic should
40// decide to evict that outbound peer, after the appropriate timeouts.
41// Note that we protect 4 outbound nodes from being subject to
42// this logic; this test takes advantage of that protection only
43// being applied to nodes which send headers with sufficient
44// work.
45BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction)
46{
48
49 ConnmanTestMsg& connman = static_cast<ConnmanTestMsg&>(*m_node.connman);
50 // Disable inactivity checks for this test to avoid interference
51 connman.SetPeerConnectTimeout(99999s);
52 PeerManager& peerman = *m_node.peerman;
53
54 // Mock an outbound peer
55 CAddress addr1(ip(0xa0b0c001), NODE_NONE);
56 NodeId id{0};
57 CNode dummyNode1{id++,
58 /*sock=*/nullptr,
59 addr1,
60 /*nKeyedNetGroupIn=*/0,
61 /*nLocalHostNonceIn=*/0,
62 CAddress(),
63 /*addrNameIn=*/"",
65 /*inbound_onion=*/false};
66
67 connman.Handshake(
68 /*node=*/dummyNode1,
69 /*successfully_connected=*/true,
70 /*remote_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
71 /*local_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
72 /*version=*/PROTOCOL_VERSION,
73 /*relay_txs=*/true);
74
75 // This test requires that we have a chain with non-zero work.
76 {
78 BOOST_CHECK(m_node.chainman->ActiveChain().Tip() != nullptr);
79 BOOST_CHECK(m_node.chainman->ActiveChain().Tip()->nChainWork > 0);
80 }
81
82 // Test starts here
83 BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in getheaders
84
85 {
86 LOCK(dummyNode1.cs_vSend);
87 const auto& [to_send, _more, _msg_type] = dummyNode1.m_transport->GetBytesToSend(false);
88 BOOST_CHECK(!to_send.empty());
89 }
90 connman.FlushSendBuffer(dummyNode1);
91
92 int64_t nStartTime = GetTime();
93 // Wait 21 minutes
94 SetMockTime(nStartTime+21*60);
95 BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in getheaders
96 {
97 LOCK(dummyNode1.cs_vSend);
98 const auto& [to_send, _more, _msg_type] = dummyNode1.m_transport->GetBytesToSend(false);
99 BOOST_CHECK(!to_send.empty());
100 }
101 // Wait 3 more minutes
102 SetMockTime(nStartTime+24*60);
103 BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in disconnect
104 BOOST_CHECK(dummyNode1.fDisconnect == true);
105
106 peerman.FinalizeNode(dummyNode1);
107}
108
109static void AddRandomOutboundPeer(NodeId& id, std::vector<CNode*>& vNodes, PeerManager& peerLogic, ConnmanTestMsg& connman, ConnectionType connType, bool onion_peer = false)
110{
111 CAddress addr;
112
113 if (onion_peer) {
115 BOOST_REQUIRE(addr.SetSpecial(OnionToString(tor_addr)));
116 }
117
118 while (!addr.IsRoutable()) {
120 }
121
122 vNodes.emplace_back(new CNode{id++,
123 /*sock=*/nullptr,
124 addr,
125 /*nKeyedNetGroupIn=*/0,
126 /*nLocalHostNonceIn=*/0,
127 CAddress(),
128 /*addrNameIn=*/"",
129 connType,
130 /*inbound_onion=*/false});
131 CNode &node = *vNodes.back();
132 node.SetCommonVersion(PROTOCOL_VERSION);
133
135 node.fSuccessfullyConnected = true;
136
137 connman.AddTestNode(node);
138}
139
140BOOST_AUTO_TEST_CASE(stale_tip_peer_management)
141{
142 NodeId id{0};
143 auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman, Params());
144 auto peerLogic = PeerManager::make(*connman, *m_node.addrman, nullptr, *m_node.chainman, *m_node.mempool, *m_node.warnings, {});
145
146 constexpr int max_outbound_full_relay = MAX_OUTBOUND_FULL_RELAY_CONNECTIONS;
147 CConnman::Options options;
149
150 const auto time_init{GetTime<std::chrono::seconds>()};
151 SetMockTime(time_init);
152 const auto time_later{time_init + 3 * std::chrono::seconds{m_node.chainman->GetConsensus().nPowTargetSpacing} + 1s};
153 connman->Init(options);
154 std::vector<CNode *> vNodes;
155
156 // Mock some outbound peers
157 for (int i = 0; i < max_outbound_full_relay; ++i) {
158 AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY);
159 }
160
161 peerLogic->CheckForStaleTipAndEvictPeers();
162
163 // No nodes should be marked for disconnection while we have no extra peers
164 for (const CNode *node : vNodes) {
165 BOOST_CHECK(node->fDisconnect == false);
166 }
167
168 SetMockTime(time_later);
169
170 // Now tip should definitely be stale, and we should look for an extra
171 // outbound peer
172 peerLogic->CheckForStaleTipAndEvictPeers();
173 BOOST_CHECK(connman->GetTryNewOutboundPeer());
174
175 // Still no peers should be marked for disconnection
176 for (const CNode *node : vNodes) {
177 BOOST_CHECK(node->fDisconnect == false);
178 }
179
180 // If we add one more peer, something should get marked for eviction
181 // on the next check (since we're mocking the time to be in the future, the
182 // required time connected check should be satisfied).
183 SetMockTime(time_init);
184 AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY);
185 SetMockTime(time_later);
186
187 peerLogic->CheckForStaleTipAndEvictPeers();
188 for (int i = 0; i < max_outbound_full_relay; ++i) {
189 BOOST_CHECK(vNodes[i]->fDisconnect == false);
190 }
191 // Last added node should get marked for eviction
192 BOOST_CHECK(vNodes.back()->fDisconnect == true);
193
194 vNodes.back()->fDisconnect = false;
195
196 // Update the last announced block time for the last
197 // peer, and check that the next newest node gets evicted.
198 peerLogic->UpdateLastBlockAnnounceTime(vNodes.back()->GetId(), GetTime());
199
200 peerLogic->CheckForStaleTipAndEvictPeers();
201 for (int i = 0; i < max_outbound_full_relay - 1; ++i) {
202 BOOST_CHECK(vNodes[i]->fDisconnect == false);
203 }
204 BOOST_CHECK(vNodes[max_outbound_full_relay-1]->fDisconnect == true);
205 BOOST_CHECK(vNodes.back()->fDisconnect == false);
206
207 vNodes[max_outbound_full_relay - 1]->fDisconnect = false;
208
209 // Add an onion peer, that will be protected because it is the only one for
210 // its network, so another peer gets disconnected instead.
211 SetMockTime(time_init);
212 AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY, /*onion_peer=*/true);
213 SetMockTime(time_later);
214 peerLogic->CheckForStaleTipAndEvictPeers();
215
216 for (int i = 0; i < max_outbound_full_relay - 2; ++i) {
217 BOOST_CHECK(vNodes[i]->fDisconnect == false);
218 }
219 BOOST_CHECK(vNodes[max_outbound_full_relay - 2]->fDisconnect == false);
220 BOOST_CHECK(vNodes[max_outbound_full_relay - 1]->fDisconnect == true);
221 BOOST_CHECK(vNodes[max_outbound_full_relay]->fDisconnect == false);
222
223 // Add a second onion peer which won't be protected
224 SetMockTime(time_init);
225 AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY, /*onion_peer=*/true);
226 SetMockTime(time_later);
227 peerLogic->CheckForStaleTipAndEvictPeers();
228
229 BOOST_CHECK(vNodes.back()->fDisconnect == true);
230
231 for (const CNode *node : vNodes) {
232 peerLogic->FinalizeNode(*node);
233 }
234
235 connman->ClearTestNodes();
236}
237
238BOOST_AUTO_TEST_CASE(block_relay_only_eviction)
239{
240 NodeId id{0};
241 auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman, Params());
242 auto peerLogic = PeerManager::make(*connman, *m_node.addrman, nullptr, *m_node.chainman, *m_node.mempool, *m_node.warnings, {});
243
244 constexpr int max_outbound_block_relay{MAX_BLOCK_RELAY_ONLY_CONNECTIONS};
245 constexpr int64_t MINIMUM_CONNECT_TIME{30};
246 CConnman::Options options;
248
249 connman->Init(options);
250 std::vector<CNode*> vNodes;
251
252 // Add block-relay-only peers up to the limit
253 for (int i = 0; i < max_outbound_block_relay; ++i) {
254 AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::BLOCK_RELAY);
255 }
256 peerLogic->CheckForStaleTipAndEvictPeers();
257
258 for (int i = 0; i < max_outbound_block_relay; ++i) {
259 BOOST_CHECK(vNodes[i]->fDisconnect == false);
260 }
261
262 // Add an extra block-relay-only peer breaking the limit (mocks logic in ThreadOpenConnections)
263 AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::BLOCK_RELAY);
264 peerLogic->CheckForStaleTipAndEvictPeers();
265
266 // The extra peer should only get marked for eviction after MINIMUM_CONNECT_TIME
267 for (int i = 0; i < max_outbound_block_relay; ++i) {
268 BOOST_CHECK(vNodes[i]->fDisconnect == false);
269 }
270 BOOST_CHECK(vNodes.back()->fDisconnect == false);
271
273 peerLogic->CheckForStaleTipAndEvictPeers();
274 for (int i = 0; i < max_outbound_block_relay; ++i) {
275 BOOST_CHECK(vNodes[i]->fDisconnect == false);
276 }
277 BOOST_CHECK(vNodes.back()->fDisconnect == true);
278
279 // Update the last block time for the extra peer,
280 // and check that the next youngest peer gets evicted.
281 vNodes.back()->fDisconnect = false;
282 vNodes.back()->m_last_block_time = GetTime<std::chrono::seconds>();
283
284 peerLogic->CheckForStaleTipAndEvictPeers();
285 for (int i = 0; i < max_outbound_block_relay - 1; ++i) {
286 BOOST_CHECK(vNodes[i]->fDisconnect == false);
287 }
288 BOOST_CHECK(vNodes[max_outbound_block_relay - 1]->fDisconnect == true);
289 BOOST_CHECK(vNodes.back()->fDisconnect == false);
290
291 for (const CNode* node : vNodes) {
292 peerLogic->FinalizeNode(*node);
293 }
294 connman->ClearTestNodes();
295}
296
297BOOST_AUTO_TEST_CASE(peer_discouragement)
298{
300
301 auto banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
302 auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman, Params());
303 auto peerLogic = PeerManager::make(*connman, *m_node.addrman, banman.get(), *m_node.chainman, *m_node.mempool, *m_node.warnings, {});
304
305 CNetAddr tor_netaddr;
306 BOOST_REQUIRE(
307 tor_netaddr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
308 const CService tor_service{tor_netaddr, Params().GetDefaultPort()};
309
310 const std::array<CAddress, 3> addr{CAddress{ip(0xa0b0c001), NODE_NONE},
311 CAddress{ip(0xa0b0c002), NODE_NONE},
312 CAddress{tor_service, NODE_NONE}};
313
314 const CNetAddr other_addr{ip(0xa0b0ff01)}; // Not any of addr[].
315
316 std::array<CNode*, 3> nodes;
317
318 banman->ClearBanned();
319 NodeId id{0};
320 nodes[0] = new CNode{id++,
321 /*sock=*/nullptr,
322 addr[0],
323 /*nKeyedNetGroupIn=*/0,
324 /*nLocalHostNonceIn=*/0,
325 CAddress(),
326 /*addrNameIn=*/"",
328 /*inbound_onion=*/false};
330 peerLogic->InitializeNode(*nodes[0], NODE_NETWORK);
331 nodes[0]->fSuccessfullyConnected = true;
332 connman->AddTestNode(*nodes[0]);
333 peerLogic->UnitTestMisbehaving(nodes[0]->GetId()); // Should be discouraged
334 BOOST_CHECK(peerLogic->SendMessages(nodes[0]));
335
336 BOOST_CHECK(banman->IsDiscouraged(addr[0]));
337 BOOST_CHECK(nodes[0]->fDisconnect);
338 BOOST_CHECK(!banman->IsDiscouraged(other_addr)); // Different address, not discouraged
339
340 nodes[1] = new CNode{id++,
341 /*sock=*/nullptr,
342 addr[1],
343 /*nKeyedNetGroupIn=*/1,
344 /*nLocalHostNonceIn=*/1,
345 CAddress(),
346 /*addrNameIn=*/"",
348 /*inbound_onion=*/false};
350 peerLogic->InitializeNode(*nodes[1], NODE_NETWORK);
351 nodes[1]->fSuccessfullyConnected = true;
352 connman->AddTestNode(*nodes[1]);
353 BOOST_CHECK(peerLogic->SendMessages(nodes[1]));
354 // [0] is still discouraged/disconnected.
355 BOOST_CHECK(banman->IsDiscouraged(addr[0]));
356 BOOST_CHECK(nodes[0]->fDisconnect);
357 // [1] is not discouraged/disconnected yet.
358 BOOST_CHECK(!banman->IsDiscouraged(addr[1]));
359 BOOST_CHECK(!nodes[1]->fDisconnect);
360 peerLogic->UnitTestMisbehaving(nodes[1]->GetId());
361 BOOST_CHECK(peerLogic->SendMessages(nodes[1]));
362 // Expect both [0] and [1] to be discouraged/disconnected now.
363 BOOST_CHECK(banman->IsDiscouraged(addr[0]));
364 BOOST_CHECK(nodes[0]->fDisconnect);
365 BOOST_CHECK(banman->IsDiscouraged(addr[1]));
366 BOOST_CHECK(nodes[1]->fDisconnect);
367
368 // Make sure non-IP peers are discouraged and disconnected properly.
369
370 nodes[2] = new CNode{id++,
371 /*sock=*/nullptr,
372 addr[2],
373 /*nKeyedNetGroupIn=*/1,
374 /*nLocalHostNonceIn=*/1,
375 CAddress(),
376 /*addrNameIn=*/"",
378 /*inbound_onion=*/false};
380 peerLogic->InitializeNode(*nodes[2], NODE_NETWORK);
381 nodes[2]->fSuccessfullyConnected = true;
382 connman->AddTestNode(*nodes[2]);
383 peerLogic->UnitTestMisbehaving(nodes[2]->GetId());
384 BOOST_CHECK(peerLogic->SendMessages(nodes[2]));
385 BOOST_CHECK(banman->IsDiscouraged(addr[0]));
386 BOOST_CHECK(banman->IsDiscouraged(addr[1]));
387 BOOST_CHECK(banman->IsDiscouraged(addr[2]));
388 BOOST_CHECK(nodes[0]->fDisconnect);
389 BOOST_CHECK(nodes[1]->fDisconnect);
390 BOOST_CHECK(nodes[2]->fDisconnect);
391
392 for (CNode* node : nodes) {
393 peerLogic->FinalizeNode(*node);
394 }
395 connman->ClearTestNodes();
396}
397
399{
401
402 auto banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
403 auto connman = std::make_unique<CConnman>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman, Params());
404 auto peerLogic = PeerManager::make(*connman, *m_node.addrman, banman.get(), *m_node.chainman, *m_node.mempool, *m_node.warnings, {});
405
406 banman->ClearBanned();
407 int64_t nStartTime = GetTime();
408 SetMockTime(nStartTime); // Overrides future calls to GetTime()
409
410 CAddress addr(ip(0xa0b0c001), NODE_NONE);
411 NodeId id{0};
412 CNode dummyNode{id++,
413 /*sock=*/nullptr,
414 addr,
415 /*nKeyedNetGroupIn=*/4,
416 /*nLocalHostNonceIn=*/4,
417 CAddress(),
418 /*addrNameIn=*/"",
420 /*inbound_onion=*/false};
422 peerLogic->InitializeNode(dummyNode, NODE_NETWORK);
423 dummyNode.fSuccessfullyConnected = true;
424
425 peerLogic->UnitTestMisbehaving(dummyNode.GetId());
426 BOOST_CHECK(peerLogic->SendMessages(&dummyNode));
427 BOOST_CHECK(banman->IsDiscouraged(addr));
428
429 peerLogic->FinalizeNode(dummyNode);
430}
431
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition banman.h:19
node::NodeContext m_node
const CChainParams & Params()
Return the currently selected parameters.
A CService with information about it as peer.
Definition protocol.h:367
uint16_t GetDefaultPort() const
Definition chainparams.h:95
Network address.
Definition netaddress.h:112
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
bool IsRoutable() const
Information about a peer.
Definition net.h:670
void SetCommonVersion(int greatest_common_version)
Definition net.h:916
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:531
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition net.h:992
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
virtual void InitializeNode(const CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state)
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, node::Warnings &warnings, Options opts)
std::vector< B > randbytes(size_t len) noexcept
Generate random bytes.
Definition random.h:297
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition random.h:204
ConnectionType
Different types of connections to a peer.
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ INBOUND
Inbound connections are those initiated by a peer.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition cs_main.cpp:8
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction)
static void AddRandomOutboundPeer(NodeId &id, std::vector< CNode * > &vNodes, PeerManager &peerLogic, ConnmanTestMsg &connman, ConnectionType connType, bool onion_peer=false)
static CService ip(uint32_t i)
static const std::string addr1
Definition key_tests.cpp:29
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition net.h:77
int64_t NodeId
Definition net.h:97
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition net.h:67
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition net.h:71
static constexpr auto MINIMUM_CONNECT_TIME
Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict.
std::string OnionToString(Span< const uint8_t > addr)
static constexpr size_t ADDR_TORV3_SIZE
Size of TORv3 address (in bytes).
Definition netaddress.h:92
#define BOOST_CHECK(expr)
Definition object.cpp:17
ServiceFlags
nServices flags
Definition protocol.h:309
@ NODE_NONE
Definition protocol.h:312
@ NODE_WITNESS
Definition protocol.h:320
@ NODE_NETWORK
Definition protocol.h:315
static const int PROTOCOL_VERSION
network protocol versioning
int m_max_automatic_connections
Definition net.h:1039
void AddTestNode(CNode &node)
Definition net.h:53
void FlushSendBuffer(CNode &node) const
Definition net.cpp:79
void SetPeerConnectTimeout(std::chrono::seconds timeout)
Definition net.h:42
Testing setup that configures a complete environment.
std::unique_ptr< CConnman > connman
Definition context.h:64
std::unique_ptr< CTxMemPool > mempool
Definition context.h:65
std::unique_ptr< AddrMan > addrman
Definition context.h:63
std::unique_ptr< ChainstateManager > chainman
Definition context.h:69
std::unique_ptr< node::Warnings > warnings
Manages all the node warnings.
Definition context.h:88
std::unique_ptr< PeerManager > peerman
Definition context.h:68
std::unique_ptr< const NetGroupManager > netgroupman
Definition context.h:66
#define LOCK(cs)
Definition sync.h:257
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
Definition random.cpp:14
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition time.cpp:44
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition time.cpp:32