Line data Source code
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 <test/util/net.h>
16 : #include <test/util/setup_common.h>
17 : #include <timedata.h>
18 : #include <util/string.h>
19 : #include <util/system.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 :
28 :
29 17 : static CService ip(uint32_t i)
30 : {
31 : struct in_addr s;
32 17 : s.s_addr = i;
33 17 : return CService(CNetAddr(s), Params().GetDefaultPort());
34 0 : }
35 :
36 146 : 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 149 : BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction)
47 : {
48 1 : LOCK(NetEventsInterface::g_msgproc_mutex);
49 :
50 1 : ConnmanTestMsg& connman = static_cast<ConnmanTestMsg&>(*m_node.connman);
51 : // Disable inactivity checks for this test to avoid interference
52 1 : connman.SetPeerConnectTimeout(99999s);
53 1 : PeerManager& peerman = *m_node.peerman;
54 :
55 : // Mock an outbound peer
56 1 : CAddress addr1(ip(0xa0b0c001), NODE_NONE);
57 1 : NodeId id{0};
58 2 : CNode dummyNode1{id++,
59 1 : /*sock=*/nullptr,
60 : addr1,
61 : /*nKeyedNetGroupIn=*/0,
62 : /*nLocalHostNonceIn=*/0,
63 1 : CAddress(),
64 1 : /*addrNameIn=*/"",
65 : ConnectionType::OUTBOUND_FULL_RELAY,
66 : /*inbound_onion=*/false};
67 :
68 1 : connman.Handshake(
69 : /*node=*/dummyNode1,
70 : /*successfully_connected=*/true,
71 : /*remote_services=*/ServiceFlags(NODE_NETWORK),
72 : /*local_services=*/ServiceFlags(NODE_NETWORK),
73 : /*version=*/PROTOCOL_VERSION,
74 : /*relay_txs=*/true);
75 1 : TestOnlyResetTimeData();
76 :
77 : // This test requires that we have a chain with non-zero work.
78 : {
79 1 : LOCK(cs_main);
80 1 : BOOST_CHECK(m_node.chainman->ActiveChain().Tip() != nullptr);
81 1 : BOOST_CHECK(m_node.chainman->ActiveChain().Tip()->nChainWork > 0);
82 1 : }
83 :
84 : // Test starts here
85 1 : BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in getheaders
86 :
87 : {
88 1 : LOCK(dummyNode1.cs_vSend);
89 1 : BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
90 1 : }
91 1 : connman.FlushSendBuffer(dummyNode1);
92 : {
93 1 : LOCK(dummyNode1.cs_vSend);
94 1 : BOOST_CHECK(dummyNode1.vSendMsg.empty());
95 1 : }
96 :
97 1 : int64_t nStartTime = GetTime();
98 : // Wait 21 minutes
99 1 : SetMockTime(nStartTime+21*60);
100 1 : BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in getheaders
101 : {
102 1 : LOCK(dummyNode1.cs_vSend);
103 1 : BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
104 1 : }
105 : // Wait 3 more minutes
106 1 : SetMockTime(nStartTime+24*60);
107 1 : BOOST_CHECK(peerman.SendMessages(&dummyNode1)); // should result in disconnect
108 1 : BOOST_CHECK(dummyNode1.fDisconnect == true);
109 :
110 1 : peerman.FinalizeNode(dummyNode1);
111 1 : }
112 :
113 14 : static void AddRandomOutboundPeer(NodeId& id, std::vector<CNode*>& vNodes, PeerManager& peerLogic, ConnmanTestMsg& connman, ConnectionType connType, bool onion_peer = false)
114 : {
115 14 : CAddress addr;
116 :
117 14 : if (onion_peer) {
118 2 : auto tor_addr{g_insecure_rand_ctx.randbytes(ADDR_TORV3_SIZE)};
119 2 : BOOST_REQUIRE(addr.SetSpecial(OnionToString(tor_addr)));
120 2 : }
121 :
122 26 : while (!addr.IsRoutable()) {
123 12 : addr = CAddress(ip(g_insecure_rand_ctx.randbits(32)), NODE_NONE);
124 : }
125 :
126 28 : vNodes.emplace_back(new CNode{id++,
127 14 : /*sock=*/nullptr,
128 : addr,
129 : /*nKeyedNetGroupIn=*/0,
130 : /*nLocalHostNonceIn=*/0,
131 14 : CAddress(),
132 14 : /*addrNameIn=*/"",
133 14 : connType,
134 : /*inbound_onion=*/false});
135 14 : CNode &node = *vNodes.back();
136 14 : node.SetCommonVersion(PROTOCOL_VERSION);
137 :
138 14 : peerLogic.InitializeNode(node, ServiceFlags(NODE_NETWORK));
139 14 : node.fSuccessfullyConnected = true;
140 :
141 14 : connman.AddTestNode(node);
142 14 : }
143 :
144 149 : BOOST_AUTO_TEST_CASE(stale_tip_peer_management)
145 : {
146 1 : NodeId id{0};
147 1 : const CChainParams& chainparams = Params();
148 1 : auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
149 1 : auto peerLogic = MakePeerManager(*connman, m_node, /*banman=*/nullptr, chainparams, /*ignore_incoming_txs=*/false);
150 :
151 1 : constexpr int max_outbound_full_relay = MAX_OUTBOUND_FULL_RELAY_CONNECTIONS;
152 1 : CConnman::Options options;
153 1 : options.nMaxConnections = DEFAULT_MAX_PEER_CONNECTIONS;
154 1 : options.m_max_outbound_full_relay = max_outbound_full_relay;
155 1 : options.nMaxFeeler = MAX_FEELER_CONNECTIONS;
156 :
157 1 : const auto time_init{GetTime<std::chrono::seconds>()};
158 1 : SetMockTime(time_init);
159 1 : const auto time_later{time_init + 3 * std::chrono::seconds{chainparams.GetConsensus().nPowTargetSpacing} + 1s};
160 1 : connman->Init(options);
161 1 : std::vector<CNode *> vNodes;
162 :
163 : // Mock some outbound peers
164 9 : for (int i = 0; i < max_outbound_full_relay; ++i) {
165 8 : AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY);
166 8 : }
167 :
168 1 : peerLogic->CheckForStaleTipAndEvictPeers();
169 :
170 : // No nodes should be marked for disconnection while we have no extra peers
171 9 : for (const CNode *node : vNodes) {
172 8 : BOOST_CHECK(node->fDisconnect == false);
173 : }
174 :
175 1 : SetMockTime(time_later);
176 :
177 : // Now tip should definitely be stale, and we should look for an extra
178 : // outbound peer
179 1 : peerLogic->CheckForStaleTipAndEvictPeers();
180 1 : BOOST_CHECK(connman->GetTryNewOutboundPeer());
181 :
182 : // Still no peers should be marked for disconnection
183 9 : for (const CNode *node : vNodes) {
184 8 : BOOST_CHECK(node->fDisconnect == false);
185 : }
186 :
187 : // If we add one more peer, something should get marked for eviction
188 : // on the next check (since we're mocking the time to be in the future, the
189 : // required time connected check should be satisfied).
190 1 : SetMockTime(time_init);
191 1 : AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY);
192 1 : SetMockTime(time_later);
193 :
194 1 : peerLogic->CheckForStaleTipAndEvictPeers();
195 9 : for (int i = 0; i < max_outbound_full_relay; ++i) {
196 8 : BOOST_CHECK(vNodes[i]->fDisconnect == false);
197 8 : }
198 : // Last added node should get marked for eviction
199 1 : BOOST_CHECK(vNodes.back()->fDisconnect == true);
200 :
201 1 : vNodes.back()->fDisconnect = false;
202 :
203 : // Update the last announced block time for the last
204 : // peer, and check that the next newest node gets evicted.
205 1 : peerLogic->UpdateLastBlockAnnounceTime(vNodes.back()->GetId(), GetTime());
206 :
207 1 : peerLogic->CheckForStaleTipAndEvictPeers();
208 8 : for (int i = 0; i < max_outbound_full_relay - 1; ++i) {
209 7 : BOOST_CHECK(vNodes[i]->fDisconnect == false);
210 7 : }
211 1 : BOOST_CHECK(vNodes[max_outbound_full_relay-1]->fDisconnect == true);
212 1 : BOOST_CHECK(vNodes.back()->fDisconnect == false);
213 :
214 1 : vNodes[max_outbound_full_relay - 1]->fDisconnect = false;
215 :
216 : // Add an onion peer, that will be protected because it is the only one for
217 : // its network, so another peer gets disconnected instead.
218 1 : SetMockTime(time_init);
219 1 : AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY, /*onion_peer=*/true);
220 1 : SetMockTime(time_later);
221 1 : peerLogic->CheckForStaleTipAndEvictPeers();
222 :
223 7 : for (int i = 0; i < max_outbound_full_relay - 2; ++i) {
224 6 : BOOST_CHECK(vNodes[i]->fDisconnect == false);
225 6 : }
226 1 : BOOST_CHECK(vNodes[max_outbound_full_relay - 2]->fDisconnect == false);
227 1 : BOOST_CHECK(vNodes[max_outbound_full_relay - 1]->fDisconnect == true);
228 1 : BOOST_CHECK(vNodes[max_outbound_full_relay]->fDisconnect == false);
229 :
230 : // Add a second onion peer which won't be protected
231 1 : SetMockTime(time_init);
232 1 : AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::OUTBOUND_FULL_RELAY, /*onion_peer=*/true);
233 1 : SetMockTime(time_later);
234 1 : peerLogic->CheckForStaleTipAndEvictPeers();
235 :
236 1 : BOOST_CHECK(vNodes.back()->fDisconnect == true);
237 :
238 12 : for (const CNode *node : vNodes) {
239 11 : peerLogic->FinalizeNode(*node);
240 : }
241 :
242 1 : connman->ClearTestNodes();
243 1 : }
244 :
245 149 : BOOST_AUTO_TEST_CASE(block_relay_only_eviction)
246 : {
247 1 : NodeId id{0};
248 1 : const CChainParams& chainparams = Params();
249 1 : auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
250 1 : auto peerLogic = MakePeerManager(*connman, m_node, /*banman=*/nullptr, chainparams, /*ignore_incoming_txs=*/false);
251 :
252 1 : constexpr int max_outbound_block_relay{MAX_BLOCK_RELAY_ONLY_CONNECTIONS};
253 1 : constexpr int64_t MINIMUM_CONNECT_TIME{30};
254 1 : CConnman::Options options;
255 1 : options.nMaxConnections = DEFAULT_MAX_PEER_CONNECTIONS;
256 1 : options.m_max_outbound_full_relay = MAX_OUTBOUND_FULL_RELAY_CONNECTIONS;
257 1 : options.m_max_outbound_block_relay = max_outbound_block_relay;
258 :
259 1 : connman->Init(options);
260 1 : std::vector<CNode*> vNodes;
261 :
262 : // Add block-relay-only peers up to the limit
263 3 : for (int i = 0; i < max_outbound_block_relay; ++i) {
264 2 : AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::BLOCK_RELAY);
265 2 : }
266 1 : peerLogic->CheckForStaleTipAndEvictPeers();
267 :
268 3 : for (int i = 0; i < max_outbound_block_relay; ++i) {
269 2 : BOOST_CHECK(vNodes[i]->fDisconnect == false);
270 2 : }
271 :
272 : // Add an extra block-relay-only peer breaking the limit (mocks logic in ThreadOpenConnections)
273 1 : AddRandomOutboundPeer(id, vNodes, *peerLogic, *connman, ConnectionType::BLOCK_RELAY);
274 1 : peerLogic->CheckForStaleTipAndEvictPeers();
275 :
276 : // The extra peer should only get marked for eviction after MINIMUM_CONNECT_TIME
277 3 : for (int i = 0; i < max_outbound_block_relay; ++i) {
278 2 : BOOST_CHECK(vNodes[i]->fDisconnect == false);
279 2 : }
280 1 : BOOST_CHECK(vNodes.back()->fDisconnect == false);
281 :
282 1 : SetMockTime(GetTime() + MINIMUM_CONNECT_TIME + 1);
283 1 : peerLogic->CheckForStaleTipAndEvictPeers();
284 3 : for (int i = 0; i < max_outbound_block_relay; ++i) {
285 2 : BOOST_CHECK(vNodes[i]->fDisconnect == false);
286 2 : }
287 1 : BOOST_CHECK(vNodes.back()->fDisconnect == true);
288 :
289 : // Update the last block time for the extra peer,
290 : // and check that the next youngest peer gets evicted.
291 1 : vNodes.back()->fDisconnect = false;
292 1 : vNodes.back()->m_last_block_time = GetTime<std::chrono::seconds>();
293 :
294 1 : peerLogic->CheckForStaleTipAndEvictPeers();
295 2 : for (int i = 0; i < max_outbound_block_relay - 1; ++i) {
296 1 : BOOST_CHECK(vNodes[i]->fDisconnect == false);
297 1 : }
298 1 : BOOST_CHECK(vNodes[max_outbound_block_relay - 1]->fDisconnect == true);
299 1 : BOOST_CHECK(vNodes.back()->fDisconnect == false);
300 :
301 4 : for (const CNode* node : vNodes) {
302 3 : peerLogic->FinalizeNode(*node);
303 : }
304 1 : connman->ClearTestNodes();
305 1 : }
306 :
307 149 : BOOST_AUTO_TEST_CASE(peer_discouragement)
308 : {
309 1 : LOCK(NetEventsInterface::g_msgproc_mutex);
310 :
311 1 : const CChainParams& chainparams = Params();
312 1 : auto banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
313 1 : auto connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
314 1 : auto peerLogic = MakePeerManager(*connman, m_node, banman.get(), chainparams, /*ignore_incoming_txs=*/false);
315 :
316 1 : CNetAddr tor_netaddr;
317 1 : BOOST_REQUIRE(
318 : tor_netaddr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
319 1 : const CService tor_service{tor_netaddr, Params().GetDefaultPort()};
320 :
321 3 : const std::array<CAddress, 3> addr{CAddress{ip(0xa0b0c001), NODE_NONE},
322 1 : CAddress{ip(0xa0b0c002), NODE_NONE},
323 1 : CAddress{tor_service, NODE_NONE}};
324 :
325 1 : const CNetAddr other_addr{ip(0xa0b0ff01)}; // Not any of addr[].
326 :
327 : std::array<CNode*, 3> nodes;
328 :
329 1 : banman->ClearBanned();
330 1 : NodeId id{0};
331 2 : nodes[0] = new CNode{id++,
332 1 : /*sock=*/nullptr,
333 1 : addr[0],
334 : /*nKeyedNetGroupIn=*/0,
335 : /*nLocalHostNonceIn=*/0,
336 1 : CAddress(),
337 1 : /*addrNameIn=*/"",
338 : ConnectionType::INBOUND,
339 : /*inbound_onion=*/false};
340 1 : nodes[0]->SetCommonVersion(PROTOCOL_VERSION);
341 1 : peerLogic->InitializeNode(*nodes[0], NODE_NETWORK);
342 1 : nodes[0]->fSuccessfullyConnected = true;
343 1 : connman->AddTestNode(*nodes[0]);
344 1 : peerLogic->Misbehaving(nodes[0]->GetId(), DISCOURAGEMENT_THRESHOLD); // Should be discouraged
345 1 : BOOST_CHECK(peerLogic->SendMessages(nodes[0]));
346 1 : BOOST_CHECK(banman->IsDiscouraged(addr[0]));
347 1 : BOOST_CHECK(nodes[0]->fDisconnect);
348 1 : BOOST_CHECK(!banman->IsDiscouraged(other_addr)); // Different address, not discouraged
349 :
350 2 : nodes[1] = new CNode{id++,
351 1 : /*sock=*/nullptr,
352 1 : addr[1],
353 : /*nKeyedNetGroupIn=*/1,
354 : /*nLocalHostNonceIn=*/1,
355 1 : CAddress(),
356 1 : /*addrNameIn=*/"",
357 : ConnectionType::INBOUND,
358 : /*inbound_onion=*/false};
359 1 : nodes[1]->SetCommonVersion(PROTOCOL_VERSION);
360 1 : peerLogic->InitializeNode(*nodes[1], NODE_NETWORK);
361 1 : nodes[1]->fSuccessfullyConnected = true;
362 1 : connman->AddTestNode(*nodes[1]);
363 1 : peerLogic->Misbehaving(nodes[1]->GetId(), DISCOURAGEMENT_THRESHOLD - 1);
364 1 : BOOST_CHECK(peerLogic->SendMessages(nodes[1]));
365 : // [0] is still discouraged/disconnected.
366 1 : BOOST_CHECK(banman->IsDiscouraged(addr[0]));
367 1 : BOOST_CHECK(nodes[0]->fDisconnect);
368 : // [1] is not discouraged/disconnected yet.
369 1 : BOOST_CHECK(!banman->IsDiscouraged(addr[1]));
370 1 : BOOST_CHECK(!nodes[1]->fDisconnect);
371 1 : peerLogic->Misbehaving(nodes[1]->GetId(), 1); // [1] reaches discouragement threshold
372 1 : BOOST_CHECK(peerLogic->SendMessages(nodes[1]));
373 : // Expect both [0] and [1] to be discouraged/disconnected now.
374 1 : BOOST_CHECK(banman->IsDiscouraged(addr[0]));
375 1 : BOOST_CHECK(nodes[0]->fDisconnect);
376 1 : BOOST_CHECK(banman->IsDiscouraged(addr[1]));
377 1 : BOOST_CHECK(nodes[1]->fDisconnect);
378 :
379 : // Make sure non-IP peers are discouraged and disconnected properly.
380 :
381 2 : nodes[2] = new CNode{id++,
382 1 : /*sock=*/nullptr,
383 1 : addr[2],
384 : /*nKeyedNetGroupIn=*/1,
385 : /*nLocalHostNonceIn=*/1,
386 1 : CAddress(),
387 1 : /*addrNameIn=*/"",
388 : ConnectionType::OUTBOUND_FULL_RELAY,
389 : /*inbound_onion=*/false};
390 1 : nodes[2]->SetCommonVersion(PROTOCOL_VERSION);
391 1 : peerLogic->InitializeNode(*nodes[2], NODE_NETWORK);
392 1 : nodes[2]->fSuccessfullyConnected = true;
393 1 : connman->AddTestNode(*nodes[2]);
394 1 : peerLogic->Misbehaving(nodes[2]->GetId(), DISCOURAGEMENT_THRESHOLD, /*message=*/"");
395 1 : BOOST_CHECK(peerLogic->SendMessages(nodes[2]));
396 1 : BOOST_CHECK(banman->IsDiscouraged(addr[0]));
397 1 : BOOST_CHECK(banman->IsDiscouraged(addr[1]));
398 1 : BOOST_CHECK(banman->IsDiscouraged(addr[2]));
399 1 : BOOST_CHECK(nodes[0]->fDisconnect);
400 1 : BOOST_CHECK(nodes[1]->fDisconnect);
401 1 : BOOST_CHECK(nodes[2]->fDisconnect);
402 :
403 4 : for (CNode* node : nodes) {
404 3 : peerLogic->FinalizeNode(*node);
405 : }
406 1 : connman->ClearTestNodes();
407 1 : }
408 :
409 149 : BOOST_AUTO_TEST_CASE(DoS_bantime)
410 : {
411 1 : LOCK(NetEventsInterface::g_msgproc_mutex);
412 :
413 1 : const CChainParams& chainparams = Params();
414 1 : auto banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
415 1 : auto connman = std::make_unique<CConnman>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman);
416 1 : auto peerLogic = MakePeerManager(*connman, m_node, banman.get(), chainparams, /*ignore_incoming_txs=*/false);
417 :
418 1 : banman->ClearBanned();
419 1 : int64_t nStartTime = GetTime();
420 1 : SetMockTime(nStartTime); // Overrides future calls to GetTime()
421 :
422 1 : CAddress addr(ip(0xa0b0c001), NODE_NONE);
423 1 : NodeId id{0};
424 2 : CNode dummyNode{id++,
425 1 : /*sock=*/nullptr,
426 : addr,
427 : /*nKeyedNetGroupIn=*/4,
428 : /*nLocalHostNonceIn=*/4,
429 1 : CAddress(),
430 1 : /*addrNameIn=*/"",
431 : ConnectionType::INBOUND,
432 : /*inbound_onion=*/false};
433 1 : dummyNode.SetCommonVersion(PROTOCOL_VERSION);
434 1 : peerLogic->InitializeNode(dummyNode, NODE_NETWORK);
435 1 : dummyNode.fSuccessfullyConnected = true;
436 :
437 1 : peerLogic->Misbehaving(dummyNode.GetId(), DISCOURAGEMENT_THRESHOLD);
438 1 : BOOST_CHECK(peerLogic->SendMessages(&dummyNode));
439 1 : BOOST_CHECK(banman->IsDiscouraged(addr));
440 1 : banman->ClearDiscouraged();
441 1 : BOOST_CHECK(!banman->IsDiscouraged(addr));
442 :
443 1 : peerLogic->FinalizeNode(dummyNode);
444 1 : }
445 :
446 146 : BOOST_AUTO_TEST_SUITE_END()
|