Bitcoin Core  24.1.0
P2P Digital Currency
denialofservice_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2021 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 {
48  ConnmanTestMsg& connman = static_cast<ConnmanTestMsg&>(*m_node.connman);
49  // Disable inactivity checks for this test to avoid interference
50  connman.SetPeerConnectTimeout(99999s);
51  PeerManager& peerman = *m_node.peerman;
52 
53  // Mock an outbound peer
54  CAddress addr1(ip(0xa0b0c001), NODE_NONE);
55  NodeId id{0};
56  CNode dummyNode1{id++,
57  /*sock=*/nullptr,
58  addr1,
59  /*nKeyedNetGroupIn=*/0,
60  /*nLocalHostNonceIn=*/0,
61  CAddress(),
62  /*addrNameIn=*/"",
64  /*inbound_onion=*/false};
65 
66  connman.Handshake(
67  /*node=*/dummyNode1,
68  /*successfully_connected=*/true,
69  /*remote_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
70  /*local_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
71  /*version=*/PROTOCOL_VERSION,
72  /*relay_txs=*/true);
74 
75  // This test requires that we have a chain with non-zero work.
76  {
77  LOCK(cs_main);
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  {
84  LOCK(dummyNode1.cs_sendProcessing);
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  {
97  LOCK(dummyNode1.cs_sendProcessing);
98  BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in getheaders
99  }
100  {
101  LOCK(dummyNode1.cs_vSend);
102  BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
103  }
104  // Wait 3 more minutes
105  SetMockTime(nStartTime+24*60);
106  {
107  LOCK(dummyNode1.cs_sendProcessing);
108  BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in disconnect
109  }
110  BOOST_CHECK(dummyNode1.fDisconnect == true);
111 
112  peerman.FinalizeNode(dummyNode1);
113 }
114 
115 static void AddRandomOutboundPeer(NodeId& id, std::vector<CNode*>& vNodes, PeerManager& peerLogic, ConnmanTestMsg& connman, ConnectionType connType)
116 {
118  vNodes.emplace_back(new CNode{id++,
119  /*sock=*/nullptr,
120  addr,
121  /*nKeyedNetGroupIn=*/0,
122  /*nLocalHostNonceIn=*/0,
123  CAddress(),
124  /*addrNameIn=*/"",
125  connType,
126  /*inbound_onion=*/false});
127  CNode &node = *vNodes.back();
128  node.SetCommonVersion(PROTOCOL_VERSION);
129 
131  node.fSuccessfullyConnected = true;
132 
133  connman.AddTestNode(node);
134 }
135 
136 BOOST_AUTO_TEST_CASE(stale_tip_peer_management)
137 {
138  NodeId id{0};
139  auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
140  auto peerLogic = PeerManager::make(*connman, *m_node.addrman, nullptr,
141  *m_node.chainman, *m_node.mempool, false);
142 
143  constexpr int max_outbound_full_relay = MAX_OUTBOUND_FULL_RELAY_CONNECTIONS;
144  CConnman::Options options;
146  options.m_max_outbound_full_relay = max_outbound_full_relay;
148 
149  const auto time_init{GetTime<std::chrono::seconds>()};
150  SetMockTime(time_init);
151  const auto time_later{time_init + 3 * std::chrono::seconds{m_node.chainman->GetConsensus().nPowTargetSpacing} + 1s};
152  connman->Init(options);
153  std::vector<CNode *> vNodes;
154 
155  // Mock some outbound peers
156  for (int i = 0; i < max_outbound_full_relay; ++i) {
157  AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY);
158  }
159 
160  peerLogic->CheckForStaleTipAndEvictPeers();
161 
162  // No nodes should be marked for disconnection while we have no extra peers
163  for (const CNode *node : vNodes) {
164  BOOST_CHECK(node->fDisconnect == false);
165  }
166 
167  SetMockTime(time_later);
168 
169  // Now tip should definitely be stale, and we should look for an extra
170  // outbound peer
171  peerLogic->CheckForStaleTipAndEvictPeers();
172  BOOST_CHECK(connman->GetTryNewOutboundPeer());
173 
174  // Still no peers should be marked for disconnection
175  for (const CNode *node : vNodes) {
176  BOOST_CHECK(node->fDisconnect == false);
177  }
178 
179  // If we add one more peer, something should get marked for eviction
180  // on the next check (since we're mocking the time to be in the future, the
181  // required time connected check should be satisfied).
182  SetMockTime(time_init);
183  AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY);
184  SetMockTime(time_later);
185 
186  peerLogic->CheckForStaleTipAndEvictPeers();
187  for (int i = 0; i < max_outbound_full_relay; ++i) {
188  BOOST_CHECK(vNodes[i]->fDisconnect == false);
189  }
190  // Last added node should get marked for eviction
191  BOOST_CHECK(vNodes.back()->fDisconnect == true);
192 
193  vNodes.back()->fDisconnect = false;
194 
195  // Update the last announced block time for the last
196  // peer, and check that the next newest node gets evicted.
197  peerLogic->UpdateLastBlockAnnounceTime(vNodes.back()->GetId(), GetTime());
198 
199  peerLogic->CheckForStaleTipAndEvictPeers();
200  for (int i = 0; i < max_outbound_full_relay - 1; ++i) {
201  BOOST_CHECK(vNodes[i]->fDisconnect == false);
202  }
203  BOOST_CHECK(vNodes[max_outbound_full_relay-1]->fDisconnect == true);
204  BOOST_CHECK(vNodes.back()->fDisconnect == false);
205 
206  for (const CNode *node : vNodes) {
207  peerLogic->FinalizeNode(*node);
208  }
209 
210  connman->ClearTestNodes();
211 }
212 
213 BOOST_AUTO_TEST_CASE(block_relay_only_eviction)
214 {
215  NodeId id{0};
216  auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
217  auto peerLogic = PeerManager::make(*connman, *m_node.addrman, nullptr,
218  *m_node.chainman, *m_node.mempool, false);
219 
220  constexpr int max_outbound_block_relay{MAX_BLOCK_RELAY_ONLY_CONNECTIONS};
221  constexpr int64_t MINIMUM_CONNECT_TIME{30};
222  CConnman::Options options;
225  options.m_max_outbound_block_relay = max_outbound_block_relay;
226 
227  connman->Init(options);
228  std::vector<CNode*> vNodes;
229 
230  // Add block-relay-only peers up to the limit
231  for (int i = 0; i < max_outbound_block_relay; ++i) {
232  AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::BLOCK_RELAY);
233  }
234  peerLogic->CheckForStaleTipAndEvictPeers();
235 
236  for (int i = 0; i < max_outbound_block_relay; ++i) {
237  BOOST_CHECK(vNodes[i]->fDisconnect == false);
238  }
239 
240  // Add an extra block-relay-only peer breaking the limit (mocks logic in ThreadOpenConnections)
241  AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::BLOCK_RELAY);
242  peerLogic->CheckForStaleTipAndEvictPeers();
243 
244  // The extra peer should only get marked for eviction after MINIMUM_CONNECT_TIME
245  for (int i = 0; i < max_outbound_block_relay; ++i) {
246  BOOST_CHECK(vNodes[i]->fDisconnect == false);
247  }
248  BOOST_CHECK(vNodes.back()->fDisconnect == false);
249 
251  peerLogic->CheckForStaleTipAndEvictPeers();
252  for (int i = 0; i < max_outbound_block_relay; ++i) {
253  BOOST_CHECK(vNodes[i]->fDisconnect == false);
254  }
255  BOOST_CHECK(vNodes.back()->fDisconnect == true);
256 
257  // Update the last block time for the extra peer,
258  // and check that the next youngest peer gets evicted.
259  vNodes.back()->fDisconnect = false;
260  vNodes.back()->m_last_block_time = GetTime<std::chrono::seconds>();
261 
262  peerLogic->CheckForStaleTipAndEvictPeers();
263  for (int i = 0; i < max_outbound_block_relay - 1; ++i) {
264  BOOST_CHECK(vNodes[i]->fDisconnect == false);
265  }
266  BOOST_CHECK(vNodes[max_outbound_block_relay - 1]->fDisconnect == true);
267  BOOST_CHECK(vNodes.back()->fDisconnect == false);
268 
269  for (const CNode* node : vNodes) {
270  peerLogic->FinalizeNode(*node);
271  }
272  connman->ClearTestNodes();
273 }
274 
275 BOOST_AUTO_TEST_CASE(peer_discouragement)
276 {
277  auto banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
278  auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
279  auto peerLogic = PeerManager::make(*connman, *m_node.addrman, banman.get(),
280  *m_node.chainman, *m_node.mempool, false);
281 
282  CNetAddr tor_netaddr;
283  BOOST_REQUIRE(
284  tor_netaddr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
285  const CService tor_service{tor_netaddr, Params().GetDefaultPort()};
286 
287  const std::array<CAddress, 3> addr{CAddress{ip(0xa0b0c001), NODE_NONE},
288  CAddress{ip(0xa0b0c002), NODE_NONE},
289  CAddress{tor_service, NODE_NONE}};
290 
291  const CNetAddr other_addr{ip(0xa0b0ff01)}; // Not any of addr[].
292 
293  std::array<CNode*, 3> nodes;
294 
295  banman->ClearBanned();
296  NodeId id{0};
297  nodes[0] = new CNode{id++,
298  /*sock=*/nullptr,
299  addr[0],
300  /*nKeyedNetGroupIn=*/0,
301  /*nLocalHostNonceIn=*/0,
302  CAddress(),
303  /*addrNameIn=*/"",
305  /*inbound_onion=*/false};
306  nodes[0]->SetCommonVersion(PROTOCOL_VERSION);
307  peerLogic->InitializeNode(*nodes[0], NODE_NETWORK);
308  nodes[0]->fSuccessfullyConnected = true;
309  connman->AddTestNode(*nodes[0]);
310  peerLogic->UnitTestMisbehaving(nodes[0]->GetId(), DISCOURAGEMENT_THRESHOLD); // Should be discouraged
311  {
312  LOCK(nodes[0]->cs_sendProcessing);
313  BOOST_CHECK(peerLogic->SendMessages(nodes[0]));
314  }
315  BOOST_CHECK(banman->IsDiscouraged(addr[0]));
316  BOOST_CHECK(nodes[0]->fDisconnect);
317  BOOST_CHECK(!banman->IsDiscouraged(other_addr)); // Different address, not discouraged
318 
319  nodes[1] = new CNode{id++,
320  /*sock=*/nullptr,
321  addr[1],
322  /*nKeyedNetGroupIn=*/1,
323  /*nLocalHostNonceIn=*/1,
324  CAddress(),
325  /*addrNameIn=*/"",
327  /*inbound_onion=*/false};
328  nodes[1]->SetCommonVersion(PROTOCOL_VERSION);
329  peerLogic->InitializeNode(*nodes[1], NODE_NETWORK);
330  nodes[1]->fSuccessfullyConnected = true;
331  connman->AddTestNode(*nodes[1]);
332  peerLogic->UnitTestMisbehaving(nodes[1]->GetId(), DISCOURAGEMENT_THRESHOLD - 1);
333  {
334  LOCK(nodes[1]->cs_sendProcessing);
335  BOOST_CHECK(peerLogic->SendMessages(nodes[1]));
336  }
337  // [0] is still discouraged/disconnected.
338  BOOST_CHECK(banman->IsDiscouraged(addr[0]));
339  BOOST_CHECK(nodes[0]->fDisconnect);
340  // [1] is not discouraged/disconnected yet.
341  BOOST_CHECK(!banman->IsDiscouraged(addr[1]));
342  BOOST_CHECK(!nodes[1]->fDisconnect);
343  peerLogic->UnitTestMisbehaving(nodes[1]->GetId(), 1); // [1] reaches discouragement threshold
344  {
345  LOCK(nodes[1]->cs_sendProcessing);
346  BOOST_CHECK(peerLogic->SendMessages(nodes[1]));
347  }
348  // Expect both [0] and [1] to be discouraged/disconnected now.
349  BOOST_CHECK(banman->IsDiscouraged(addr[0]));
350  BOOST_CHECK(nodes[0]->fDisconnect);
351  BOOST_CHECK(banman->IsDiscouraged(addr[1]));
352  BOOST_CHECK(nodes[1]->fDisconnect);
353 
354  // Make sure non-IP peers are discouraged and disconnected properly.
355 
356  nodes[2] = new CNode{id++,
357  /*sock=*/nullptr,
358  addr[2],
359  /*nKeyedNetGroupIn=*/1,
360  /*nLocalHostNonceIn=*/1,
361  CAddress(),
362  /*addrNameIn=*/"",
364  /*inbound_onion=*/false};
365  nodes[2]->SetCommonVersion(PROTOCOL_VERSION);
366  peerLogic->InitializeNode(*nodes[2], NODE_NETWORK);
367  nodes[2]->fSuccessfullyConnected = true;
368  connman->AddTestNode(*nodes[2]);
369  peerLogic->UnitTestMisbehaving(nodes[2]->GetId(), DISCOURAGEMENT_THRESHOLD);
370  {
371  LOCK(nodes[2]->cs_sendProcessing);
372  BOOST_CHECK(peerLogic->SendMessages(nodes[2]));
373  }
374  BOOST_CHECK(banman->IsDiscouraged(addr[0]));
375  BOOST_CHECK(banman->IsDiscouraged(addr[1]));
376  BOOST_CHECK(banman->IsDiscouraged(addr[2]));
377  BOOST_CHECK(nodes[0]->fDisconnect);
378  BOOST_CHECK(nodes[1]->fDisconnect);
379  BOOST_CHECK(nodes[2]->fDisconnect);
380 
381  for (CNode* node : nodes) {
382  peerLogic->FinalizeNode(*node);
383  }
384  connman->ClearTestNodes();
385 }
386 
388 {
389  auto banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
390  auto connman = std::make_unique<CConnman>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
391  auto peerLogic = PeerManager::make(*connman, *m_node.addrman, banman.get(),
392  *m_node.chainman, *m_node.mempool, false);
393 
394  banman->ClearBanned();
395  int64_t nStartTime = GetTime();
396  SetMockTime(nStartTime); // Overrides future calls to GetTime()
397 
398  CAddress addr(ip(0xa0b0c001), NODE_NONE);
399  NodeId id{0};
400  CNode dummyNode{id++,
401  /*sock=*/nullptr,
402  addr,
403  /*nKeyedNetGroupIn=*/4,
404  /*nLocalHostNonceIn=*/4,
405  CAddress(),
406  /*addrNameIn=*/"",
408  /*inbound_onion=*/false};
409  dummyNode.SetCommonVersion(PROTOCOL_VERSION);
410  peerLogic->InitializeNode(dummyNode, NODE_NETWORK);
411  dummyNode.fSuccessfullyConnected = true;
412 
413  peerLogic->UnitTestMisbehaving(dummyNode.GetId(), DISCOURAGEMENT_THRESHOLD);
414  {
415  LOCK(dummyNode.cs_sendProcessing);
416  BOOST_CHECK(peerLogic->SendMessages(&dummyNode));
417  }
418  BOOST_CHECK(banman->IsDiscouraged(addr));
419 
420  peerLogic->FinalizeNode(dummyNode);
421 }
422 
int m_max_outbound_full_relay
Definition: net.h:674
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:71
void SetPeerConnectTimeout(std::chrono::seconds timeout)
Definition: net.h:23
BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction)
ServiceFlags
nServices flags
Definition: protocol.h:267
Inbound connections are those initiated by a peer.
int m_max_outbound_block_relay
Definition: net.h:675
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
void TestOnlyResetTimeData()
Reset the internal state of GetTimeOffset(), GetAdjustedTime() and AddTimeData(). ...
Definition: timedata.cpp:113
std::unique_ptr< const NetGroupManager > netgroupman
Definition: context.h:51
std::unique_ptr< AddrMan > addrman
Definition: context.h:48
int nMaxConnections
Definition: net.h:673
These are the default connections that we use to connect with the network.
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:73
uint16_t GetDefaultPort() const
Definition: chainparams.h:84
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:50
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:91
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:195
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
virtual void InitializeNode(CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
static const std::string addr1
Definition: key_tests.cpp:24
#define LOCK(cs)
Definition: sync.h:261
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:520
BOOST_AUTO_TEST_SUITE_END()
static void AddRandomOutboundPeer(NodeId &id, std::vector< CNode *> &vNodes, PeerManager &peerLogic, ConnmanTestMsg &connman, ConnectionType connType)
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
A CService with information about it as peer.
Definition: protocol.h:354
int nMaxFeeler
Definition: net.h:677
static CService ip(uint32_t i)
int64_t NodeId
Definition: net.h:93
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:77
static const int DISCOURAGEMENT_THRESHOLD
Threshold for marking a node to be discouraged, e.g.
Definition: init.h:25
Network address.
Definition: netaddress.h:117
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: banman.h:19
const CChainParams & Params()
Return the currently selected parameters.
void Handshake(CNode &node, bool successfully_connected, ServiceFlags remote_services, ServiceFlags local_services, int32_t version, bool relay_txs)
Definition: net.cpp:16
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:121
ConnectionType
Different types of connections to a peer.
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we&#39;ll relay everything (blocks, tx, addrs, etc)
Definition: net.h:67
std::unique_ptr< CConnman > connman
Definition: context.h:49
Information about a peer.
Definition: net.h:347
static constexpr auto MINIMUM_CONNECT_TIME
Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict...
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:117
void AddTestNode(CNode &node)
Definition: net.h:28
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:54
Testing setup that configures a complete environment.
Definition: setup_common.h:109
We use block-relay-only connections to help prevent against partition attacks.
#define BOOST_CHECK(expr)
Definition: object.cpp:16
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
Send queued protocol messages to a given node.
std::unique_ptr< PeerManager > peerman
Definition: context.h:53