Bitcoin Core  24.99.0
P2P Digital Currency
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 <net.h>
10 #include <net_processing.h>
11 #include <pubkey.h>
12 #include <script/sign.h>
13 #include <script/signingprovider.h>
14 #include <script/standard.h>
15 #include <serialize.h>
16 #include <test/util/net.h>
17 #include <test/util/setup_common.h>
18 #include <timedata.h>
19 #include <util/string.h>
20 #include <util/system.h>
21 #include <util/time.h>
22 #include <validation.h>
23 
24 #include <array>
25 #include <stdint.h>
26 
27 #include <boost/test/unit_test.hpp>
28 
29 static CService ip(uint32_t i)
30 {
31  struct in_addr s;
32  s.s_addr = i;
33  return CService(CNetAddr(s), Params().GetDefaultPort());
34 }
35 
36 BOOST_FIXTURE_TEST_SUITE(denialofservice_tests, TestingSetup)
37 
38 // Test eviction of an outbound peer whose chain never advances
39 // Mock a node connection, and use mocktime to simulate a peer
40 // which never sends any headers messages. PeerLogic should
41 // decide to evict that outbound peer, after the appropriate timeouts.
42 // Note that we protect 4 outbound nodes from being subject to
43 // this logic; this test takes advantage of that protection only
44 // being applied to nodes which send headers with sufficient
45 // work.
46 BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction)
47 {
49 
50  ConnmanTestMsg& connman = static_cast<ConnmanTestMsg&>(*m_node.connman);
51  // Disable inactivity checks for this test to avoid interference
52  connman.SetPeerConnectTimeout(99999s);
53  PeerManager& peerman = *m_node.peerman;
54 
55  // Mock an outbound peer
56  CAddress addr1(ip(0xa0b0c001), NODE_NONE);
57  NodeId id{0};
58  CNode dummyNode1{id++,
59  /*sock=*/nullptr,
60  addr1,
61  /*nKeyedNetGroupIn=*/0,
62  /*nLocalHostNonceIn=*/0,
63  CAddress(),
64  /*addrNameIn=*/"",
66  /*inbound_onion=*/false};
67 
68  connman.Handshake(
69  /*node=*/dummyNode1,
70  /*successfully_connected=*/true,
71  /*remote_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
72  /*local_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
73  /*version=*/PROTOCOL_VERSION,
74  /*relay_txs=*/true);
76 
77  // This test requires that we have a chain with non-zero work.
78  {
79  LOCK(cs_main);
80  BOOST_CHECK(m_node.chainman->ActiveChain().Tip() != nullptr);
81  BOOST_CHECK(m_node.chainman->ActiveChain().Tip()->nChainWork > 0);
82  }
83 
84  // Test starts here
85  BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in getheaders
86 
87  {
88  LOCK(dummyNode1.cs_vSend);
89  BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
90  dummyNode1.vSendMsg.clear();
91  }
92 
93  int64_t nStartTime = GetTime();
94  // Wait 21 minutes
95  SetMockTime(nStartTime+21*60);
96  BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in getheaders
97  {
98  LOCK(dummyNode1.cs_vSend);
99  BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
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 
109 static void AddRandomOutboundPeer(NodeId& id, std::vector<CNode*>& vNodes, PeerManager& peerLogic, ConnmanTestMsg& connman, ConnectionType connType)
110 {
112  vNodes.emplace_back(new CNode{id++,
113  /*sock=*/nullptr,
114  addr,
115  /*nKeyedNetGroupIn=*/0,
116  /*nLocalHostNonceIn=*/0,
117  CAddress(),
118  /*addrNameIn=*/"",
119  connType,
120  /*inbound_onion=*/false});
121  CNode &node = *vNodes.back();
122  node.SetCommonVersion(PROTOCOL_VERSION);
123 
125  node.fSuccessfullyConnected = true;
126 
127  connman.AddTestNode(node);
128 }
129 
130 BOOST_AUTO_TEST_CASE(stale_tip_peer_management)
131 {
132  NodeId id{0};
133  auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
134  auto peerLogic = PeerManager::make(*connman, *m_node.addrman, nullptr,
135  *m_node.chainman, *m_node.mempool, false);
136 
137  constexpr int max_outbound_full_relay = MAX_OUTBOUND_FULL_RELAY_CONNECTIONS;
138  CConnman::Options options;
140  options.m_max_outbound_full_relay = max_outbound_full_relay;
142 
143  const auto time_init{GetTime<std::chrono::seconds>()};
144  SetMockTime(time_init);
145  const auto time_later{time_init + 3 * std::chrono::seconds{m_node.chainman->GetConsensus().nPowTargetSpacing} + 1s};
146  connman->Init(options);
147  std::vector<CNode *> vNodes;
148 
149  // Mock some outbound peers
150  for (int i = 0; i < max_outbound_full_relay; ++i) {
151  AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY);
152  }
153 
154  peerLogic->CheckForStaleTipAndEvictPeers();
155 
156  // No nodes should be marked for disconnection while we have no extra peers
157  for (const CNode *node : vNodes) {
158  BOOST_CHECK(node->fDisconnect == false);
159  }
160 
161  SetMockTime(time_later);
162 
163  // Now tip should definitely be stale, and we should look for an extra
164  // outbound peer
165  peerLogic->CheckForStaleTipAndEvictPeers();
166  BOOST_CHECK(connman->GetTryNewOutboundPeer());
167 
168  // Still no peers should be marked for disconnection
169  for (const CNode *node : vNodes) {
170  BOOST_CHECK(node->fDisconnect == false);
171  }
172 
173  // If we add one more peer, something should get marked for eviction
174  // on the next check (since we're mocking the time to be in the future, the
175  // required time connected check should be satisfied).
176  SetMockTime(time_init);
177  AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY);
178  SetMockTime(time_later);
179 
180  peerLogic->CheckForStaleTipAndEvictPeers();
181  for (int i = 0; i < max_outbound_full_relay; ++i) {
182  BOOST_CHECK(vNodes[i]->fDisconnect == false);
183  }
184  // Last added node should get marked for eviction
185  BOOST_CHECK(vNodes.back()->fDisconnect == true);
186 
187  vNodes.back()->fDisconnect = false;
188 
189  // Update the last announced block time for the last
190  // peer, and check that the next newest node gets evicted.
191  peerLogic->UpdateLastBlockAnnounceTime(vNodes.back()->GetId(), GetTime());
192 
193  peerLogic->CheckForStaleTipAndEvictPeers();
194  for (int i = 0; i < max_outbound_full_relay - 1; ++i) {
195  BOOST_CHECK(vNodes[i]->fDisconnect == false);
196  }
197  BOOST_CHECK(vNodes[max_outbound_full_relay-1]->fDisconnect == true);
198  BOOST_CHECK(vNodes.back()->fDisconnect == false);
199 
200  for (const CNode *node : vNodes) {
201  peerLogic->FinalizeNode(*node);
202  }
203 
204  connman->ClearTestNodes();
205 }
206 
207 BOOST_AUTO_TEST_CASE(block_relay_only_eviction)
208 {
209  NodeId id{0};
210  auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
211  auto peerLogic = PeerManager::make(*connman, *m_node.addrman, nullptr,
212  *m_node.chainman, *m_node.mempool, false);
213 
214  constexpr int max_outbound_block_relay{MAX_BLOCK_RELAY_ONLY_CONNECTIONS};
215  constexpr int64_t MINIMUM_CONNECT_TIME{30};
216  CConnman::Options options;
219  options.m_max_outbound_block_relay = max_outbound_block_relay;
220 
221  connman->Init(options);
222  std::vector<CNode*> vNodes;
223 
224  // Add block-relay-only peers up to the limit
225  for (int i = 0; i < max_outbound_block_relay; ++i) {
226  AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::BLOCK_RELAY);
227  }
228  peerLogic->CheckForStaleTipAndEvictPeers();
229 
230  for (int i = 0; i < max_outbound_block_relay; ++i) {
231  BOOST_CHECK(vNodes[i]->fDisconnect == false);
232  }
233 
234  // Add an extra block-relay-only peer breaking the limit (mocks logic in ThreadOpenConnections)
235  AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::BLOCK_RELAY);
236  peerLogic->CheckForStaleTipAndEvictPeers();
237 
238  // The extra peer should only get marked for eviction after MINIMUM_CONNECT_TIME
239  for (int i = 0; i < max_outbound_block_relay; ++i) {
240  BOOST_CHECK(vNodes[i]->fDisconnect == false);
241  }
242  BOOST_CHECK(vNodes.back()->fDisconnect == false);
243 
245  peerLogic->CheckForStaleTipAndEvictPeers();
246  for (int i = 0; i < max_outbound_block_relay; ++i) {
247  BOOST_CHECK(vNodes[i]->fDisconnect == false);
248  }
249  BOOST_CHECK(vNodes.back()->fDisconnect == true);
250 
251  // Update the last block time for the extra peer,
252  // and check that the next youngest peer gets evicted.
253  vNodes.back()->fDisconnect = false;
254  vNodes.back()->m_last_block_time = GetTime<std::chrono::seconds>();
255 
256  peerLogic->CheckForStaleTipAndEvictPeers();
257  for (int i = 0; i < max_outbound_block_relay - 1; ++i) {
258  BOOST_CHECK(vNodes[i]->fDisconnect == false);
259  }
260  BOOST_CHECK(vNodes[max_outbound_block_relay - 1]->fDisconnect == true);
261  BOOST_CHECK(vNodes.back()->fDisconnect == false);
262 
263  for (const CNode* node : vNodes) {
264  peerLogic->FinalizeNode(*node);
265  }
266  connman->ClearTestNodes();
267 }
268 
269 BOOST_AUTO_TEST_CASE(peer_discouragement)
270 {
272 
273  auto banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
274  auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
275  auto peerLogic = PeerManager::make(*connman, *m_node.addrman, banman.get(),
276  *m_node.chainman, *m_node.mempool, false);
277 
278  CNetAddr tor_netaddr;
279  BOOST_REQUIRE(
280  tor_netaddr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
281  const CService tor_service{tor_netaddr, Params().GetDefaultPort()};
282 
283  const std::array<CAddress, 3> addr{CAddress{ip(0xa0b0c001), NODE_NONE},
284  CAddress{ip(0xa0b0c002), NODE_NONE},
285  CAddress{tor_service, NODE_NONE}};
286 
287  const CNetAddr other_addr{ip(0xa0b0ff01)}; // Not any of addr[].
288 
289  std::array<CNode*, 3> nodes;
290 
291  banman->ClearBanned();
292  NodeId id{0};
293  nodes[0] = new CNode{id++,
294  /*sock=*/nullptr,
295  addr[0],
296  /*nKeyedNetGroupIn=*/0,
297  /*nLocalHostNonceIn=*/0,
298  CAddress(),
299  /*addrNameIn=*/"",
301  /*inbound_onion=*/false};
302  nodes[0]->SetCommonVersion(PROTOCOL_VERSION);
303  peerLogic->InitializeNode(*nodes[0], NODE_NETWORK);
304  nodes[0]->fSuccessfullyConnected = true;
305  connman->AddTestNode(*nodes[0]);
306  peerLogic->UnitTestMisbehaving(nodes[0]->GetId(), DISCOURAGEMENT_THRESHOLD); // Should be discouraged
307  BOOST_CHECK(peerLogic->SendMessages(nodes[0]));
308 
309  BOOST_CHECK(banman->IsDiscouraged(addr[0]));
310  BOOST_CHECK(nodes[0]->fDisconnect);
311  BOOST_CHECK(!banman->IsDiscouraged(other_addr)); // Different address, not discouraged
312 
313  nodes[1] = new CNode{id++,
314  /*sock=*/nullptr,
315  addr[1],
316  /*nKeyedNetGroupIn=*/1,
317  /*nLocalHostNonceIn=*/1,
318  CAddress(),
319  /*addrNameIn=*/"",
321  /*inbound_onion=*/false};
322  nodes[1]->SetCommonVersion(PROTOCOL_VERSION);
323  peerLogic->InitializeNode(*nodes[1], NODE_NETWORK);
324  nodes[1]->fSuccessfullyConnected = true;
325  connman->AddTestNode(*nodes[1]);
326  peerLogic->UnitTestMisbehaving(nodes[1]->GetId(), DISCOURAGEMENT_THRESHOLD - 1);
327  BOOST_CHECK(peerLogic->SendMessages(nodes[1]));
328  // [0] is still discouraged/disconnected.
329  BOOST_CHECK(banman->IsDiscouraged(addr[0]));
330  BOOST_CHECK(nodes[0]->fDisconnect);
331  // [1] is not discouraged/disconnected yet.
332  BOOST_CHECK(!banman->IsDiscouraged(addr[1]));
333  BOOST_CHECK(!nodes[1]->fDisconnect);
334  peerLogic->UnitTestMisbehaving(nodes[1]->GetId(), 1); // [1] reaches discouragement threshold
335  BOOST_CHECK(peerLogic->SendMessages(nodes[1]));
336  // Expect both [0] and [1] to be discouraged/disconnected now.
337  BOOST_CHECK(banman->IsDiscouraged(addr[0]));
338  BOOST_CHECK(nodes[0]->fDisconnect);
339  BOOST_CHECK(banman->IsDiscouraged(addr[1]));
340  BOOST_CHECK(nodes[1]->fDisconnect);
341 
342  // Make sure non-IP peers are discouraged and disconnected properly.
343 
344  nodes[2] = new CNode{id++,
345  /*sock=*/nullptr,
346  addr[2],
347  /*nKeyedNetGroupIn=*/1,
348  /*nLocalHostNonceIn=*/1,
349  CAddress(),
350  /*addrNameIn=*/"",
352  /*inbound_onion=*/false};
353  nodes[2]->SetCommonVersion(PROTOCOL_VERSION);
354  peerLogic->InitializeNode(*nodes[2], NODE_NETWORK);
355  nodes[2]->fSuccessfullyConnected = true;
356  connman->AddTestNode(*nodes[2]);
357  peerLogic->UnitTestMisbehaving(nodes[2]->GetId(), DISCOURAGEMENT_THRESHOLD);
358  BOOST_CHECK(peerLogic->SendMessages(nodes[2]));
359  BOOST_CHECK(banman->IsDiscouraged(addr[0]));
360  BOOST_CHECK(banman->IsDiscouraged(addr[1]));
361  BOOST_CHECK(banman->IsDiscouraged(addr[2]));
362  BOOST_CHECK(nodes[0]->fDisconnect);
363  BOOST_CHECK(nodes[1]->fDisconnect);
364  BOOST_CHECK(nodes[2]->fDisconnect);
365 
366  for (CNode* node : nodes) {
367  peerLogic->FinalizeNode(*node);
368  }
369  connman->ClearTestNodes();
370 }
371 
373 {
375 
376  auto banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
377  auto connman = std::make_unique<CConnman>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
378  auto peerLogic = PeerManager::make(*connman, *m_node.addrman, banman.get(),
379  *m_node.chainman, *m_node.mempool, false);
380 
381  banman->ClearBanned();
382  int64_t nStartTime = GetTime();
383  SetMockTime(nStartTime); // Overrides future calls to GetTime()
384 
385  CAddress addr(ip(0xa0b0c001), NODE_NONE);
386  NodeId id{0};
387  CNode dummyNode{id++,
388  /*sock=*/nullptr,
389  addr,
390  /*nKeyedNetGroupIn=*/4,
391  /*nLocalHostNonceIn=*/4,
392  CAddress(),
393  /*addrNameIn=*/"",
395  /*inbound_onion=*/false};
396  dummyNode.SetCommonVersion(PROTOCOL_VERSION);
397  peerLogic->InitializeNode(dummyNode, NODE_NETWORK);
398  dummyNode.fSuccessfullyConnected = true;
399 
400  peerLogic->UnitTestMisbehaving(dummyNode.GetId(), DISCOURAGEMENT_THRESHOLD);
401  BOOST_CHECK(peerLogic->SendMessages(&dummyNode));
402  BOOST_CHECK(banman->IsDiscouraged(addr));
403 
404  peerLogic->FinalizeNode(dummyNode);
405 }
406 
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: banman.h:19
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
const CChainParams & Params()
Return the currently selected parameters.
A CService with information about it as peer.
Definition: protocol.h:361
uint16_t GetDefaultPort() const
Definition: chainparams.h:84
Network address.
Definition: netaddress.h:120
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:208
Information about a peer.
Definition: net.h:347
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:523
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:195
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:630
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(CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
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:7
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)
static CService ip(uint32_t i)
static const std::string addr1
Definition: key_tests.cpp:24
Definition: init.h:25
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:76
int64_t NodeId
Definition: net.h:92
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:72
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:66
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:70
static constexpr auto MINIMUM_CONNECT_TIME
Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict.
static const int DISCOURAGEMENT_THRESHOLD
Threshold for marking a node to be discouraged, e.g.
#define BOOST_CHECK(expr)
Definition: object.cpp:17
ServiceFlags
nServices flags
Definition: protocol.h:273
@ NODE_NONE
Definition: protocol.h:276
@ NODE_WITNESS
Definition: protocol.h:286
@ NODE_NETWORK
Definition: protocol.h:279
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
int m_max_outbound_block_relay
Definition: net.h:673
int m_max_outbound_full_relay
Definition: net.h:672
int nMaxFeeler
Definition: net.h:675
int nMaxConnections
Definition: net.h:671
void AddTestNode(CNode &node)
Definition: net.h:28
void SetPeerConnectTimeout(std::chrono::seconds timeout)
Definition: net.h:23
Testing setup that configures a complete environment.
Definition: setup_common.h:108
std::unique_ptr< CConnman > connman
Definition: context.h:49
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:50
std::unique_ptr< AddrMan > addrman
Definition: context.h:48
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:54
std::unique_ptr< PeerManager > peerman
Definition: context.h:53
std::unique_ptr< const NetGroupManager > netgroupman
Definition: context.h:51
#define LOCK(cs)
Definition: sync.h:258
int64_t GetTime()
Definition: time.cpp:115
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:89
void TestOnlyResetTimeData()
Reset the internal state of GetTimeOffset(), GetAdjustedTime() and AddTimeData().
Definition: timedata.cpp:113
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12