Repository navigation
Expand file tree
/
Copy pathdenialofservice_tests.cpp
More file actions
490 lines (424 loc) · 17.4 KB
/
Copy pathdenialofservice_tests.cpp
File metadata and controls
490 lines (424 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Unit tests for denial-of-service detection/prevention code
#include <banman.h>
#include <chain.h>
#include <chainparams.h>
#include <config.h>
#include <crypto/siphash.h>
#include <keystore.h>
#include <net.h>
#include <net_processing.h>
#include <net_processing_internal.h> // for internal namespace
#include <pow.h>
#include <script/sign.h>
#include <serialize.h>
#include <util/system.h>
#include <validation.h>
#include <test/setup_common.h>
#include <boost/test/unit_test.hpp>
#include <cstdint>
#include <cstring>
struct CConnmanTest : public CConnman {
using CConnman::CConnman;
void AddNode(CNode &node) {
LOCK(cs_vNodes);
vNodes.push_back(&node);
}
void ClearNodes() {
LOCK(cs_vNodes);
for (CNode *node : vNodes) {
delete node;
}
vNodes.clear();
}
};
static CService ip(uint32_t i) {
struct in_addr s;
s.s_addr = i;
return CService(CNetAddr(s), Params().GetDefaultPort());
}
static NodeId id = 0;
BOOST_FIXTURE_TEST_SUITE(denialofservice_tests, TestingSetup)
// Test eviction of an outbound peer whose chain never advances
// Mock a node connection, and use mocktime to simulate a peer which never sends
// any headers messages. PeerLogic should decide to evict that outbound peer,
// after the appropriate timeouts.
// Note that we protect 4 outbound nodes from being subject to this logic; this
// test takes advantage of that protection only being applied to nodes which
// send headers with sufficient work.
BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction) {
const Config &config = GetConfig();
std::atomic<bool> interruptDummy(false);
auto connman = std::make_unique<CConnman>(config, 0x1337, 0x1337);
auto peerLogic = std::make_unique<PeerLogicValidation>(
connman.get(), nullptr, scheduler, false);
// Mock an outbound peer
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, ServiceFlags(NODE_NETWORK), 0, INVALID_SOCKET, addr1,
0, 0, CAddress(), "",
/*fInboundIn=*/false);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
peerLogic->InitializeNode(config, &dummyNode1);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
// This test requires that we have a chain with non-zero work.
{
LOCK(cs_main);
BOOST_CHECK(::ChainActive().Tip() != nullptr);
BOOST_CHECK(::ChainActive().Tip()->nChainWork > 0);
}
// Test starts here
{
LOCK2(cs_main, dummyNode1.cs_sendProcessing);
// should result in getheaders
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode1, interruptDummy));
}
{
LOCK2(cs_main, dummyNode1.cs_vSend);
BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
dummyNode1.vSendMsg.clear();
}
int64_t nStartTime = GetTime();
// Wait 21 minutes
SetMockTime(nStartTime + 21 * 60);
{
LOCK2(cs_main, dummyNode1.cs_sendProcessing);
// should result in getheaders
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode1, interruptDummy));
}
{
LOCK2(cs_main, dummyNode1.cs_vSend);
BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
}
// Wait 3 more minutes
SetMockTime(nStartTime + 24 * 60);
{
LOCK2(cs_main, dummyNode1.cs_sendProcessing);
// should result in disconnect
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode1, interruptDummy));
}
BOOST_CHECK(dummyNode1.fDisconnect == true);
SetMockTime(0);
bool dummy;
peerLogic->FinalizeNode(config, dummyNode1.GetId(), dummy);
}
static void AddRandomOutboundPeer(const Config &config,
std::vector<CNode *> &vNodes,
PeerLogicValidation &peerLogic,
CConnmanTest *connman) {
CAddress addr(ip(g_insecure_rand_ctx.randbits(32)), NODE_NONE);
vNodes.emplace_back(new CNode(id++, ServiceFlags(NODE_NETWORK), 0,
INVALID_SOCKET, addr, 0, 0, CAddress(), "",
/*fInboundIn=*/false));
CNode &node = *vNodes.back();
node.SetSendVersion(PROTOCOL_VERSION);
peerLogic.InitializeNode(config, &node);
node.nVersion = 1;
node.fSuccessfullyConnected = true;
connman->AddNode(node);
}
BOOST_AUTO_TEST_CASE(stale_tip_peer_management) {
const Config &config = GetConfig();
auto connman = std::make_unique<CConnmanTest>(config, 0x1337, 0x1337);
auto peerLogic = std::make_unique<PeerLogicValidation>(
connman.get(), nullptr, scheduler, false);
const Consensus::Params &consensusParams =
config.GetChainParams().GetConsensus();
constexpr int nMaxOutbound = 8;
CConnman::Options options;
options.nMaxConnections = 125;
options.nMaxOutbound = nMaxOutbound;
options.nMaxFeeler = 1;
connman->Init(options);
std::vector<CNode *> vNodes;
// Mock some outbound peers
for (int i = 0; i < nMaxOutbound; ++i) {
AddRandomOutboundPeer(config, vNodes, *peerLogic, connman.get());
}
peerLogic->CheckForStaleTipAndEvictPeers(consensusParams);
// No nodes should be marked for disconnection while we have no extra peers
for (const CNode *node : vNodes) {
BOOST_CHECK(node->fDisconnect == false);
}
SetMockTime(GetTime() + 3 * consensusParams.nPowTargetSpacing + 1);
// Now tip should definitely be stale, and we should look for an extra
// outbound peer
peerLogic->CheckForStaleTipAndEvictPeers(consensusParams);
BOOST_CHECK(connman->GetTryNewOutboundPeer());
// Still no peers should be marked for disconnection
for (const CNode *node : vNodes) {
BOOST_CHECK(node->fDisconnect == false);
}
// If we add one more peer, something should get marked for eviction
// on the next check (since we're mocking the time to be in the future, the
// required time connected check should be satisfied).
AddRandomOutboundPeer(config, vNodes, *peerLogic, connman.get());
peerLogic->CheckForStaleTipAndEvictPeers(consensusParams);
for (int i = 0; i < nMaxOutbound; ++i) {
BOOST_CHECK(vNodes[i]->fDisconnect == false);
}
// Last added node should get marked for eviction
BOOST_CHECK(vNodes.back()->fDisconnect == true);
vNodes.back()->fDisconnect = false;
// Update the last announced block time for the last
// peer, and check that the next newest node gets evicted.
internal::UpdateLastBlockAnnounceTime(vNodes.back()->GetId(), GetTime());
peerLogic->CheckForStaleTipAndEvictPeers(consensusParams);
for (int i = 0; i < nMaxOutbound - 1; ++i) {
BOOST_CHECK(vNodes[i]->fDisconnect == false);
}
BOOST_CHECK(vNodes[nMaxOutbound - 1]->fDisconnect == true);
BOOST_CHECK(vNodes.back()->fDisconnect == false);
bool dummy;
for (const CNode *node : vNodes) {
peerLogic->FinalizeNode(config, node->GetId(), dummy);
}
connman->ClearNodes();
}
BOOST_AUTO_TEST_CASE(DoS_autodiscourage) {
const Config &config = GetConfig();
std::atomic<bool> interruptDummy(false);
auto banman = std::make_unique<BanMan>(GetDataDir() / "banlist.dat",
config.GetChainParams(), nullptr,
DEFAULT_MANUAL_BANTIME);
auto connman = std::make_unique<CConnman>(config, 0x1337, 0x1337);
auto peerLogic = std::make_unique<PeerLogicValidation>(
connman.get(), banman.get(), scheduler, false);
banman->ClearAll();
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0,
CAddress(), "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
peerLogic->InitializeNode(config, &dummyNode1);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
{
LOCK(cs_main);
// Should get discouraged.
Misbehaving(dummyNode1.GetId(), 100, "");
}
{
LOCK2(cs_main, dummyNode1.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode1, interruptDummy));
}
// check discouraged but not banned
BOOST_CHECK(banman->IsDiscouraged(addr1));
BOOST_CHECK(!banman->IsBanned(addr1));
// Different IP, not discouraged.
BOOST_CHECK(!banman->IsDiscouraged(ip(0xa0b0c001 | 0x0000ff00)));
CAddress addr2(ip(0xa0b0c002), NODE_NONE);
CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1,
CAddress(), "", true);
dummyNode2.SetSendVersion(PROTOCOL_VERSION);
peerLogic->InitializeNode(config, &dummyNode2);
dummyNode2.nVersion = 1;
dummyNode2.fSuccessfullyConnected = true;
{
LOCK(cs_main);
Misbehaving(dummyNode2.GetId(), 50, "");
}
{
LOCK2(cs_main, dummyNode2.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode2, interruptDummy));
}
// 2 not discouraged yet...
BOOST_CHECK(!banman->IsDiscouraged(addr2));
// ... but 1 still should be.
BOOST_CHECK(banman->IsDiscouraged(addr1));
{
LOCK(cs_main);
Misbehaving(dummyNode2.GetId(), 50, "");
}
{
LOCK2(cs_main, dummyNode2.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode2, interruptDummy));
}
BOOST_CHECK(banman->IsDiscouraged(addr2));
BOOST_CHECK(!banman->IsBanned(addr2));
bool dummy;
peerLogic->FinalizeNode(config, dummyNode1.GetId(), dummy);
peerLogic->FinalizeNode(config, dummyNode2.GetId(), dummy);
}
BOOST_AUTO_TEST_CASE(DoS_banscore) {
const Config &config = GetConfig();
std::atomic<bool> interruptDummy(false);
auto banman = std::make_unique<BanMan>(GetDataDir() / "banlist.dat",
config.GetChainParams(), nullptr,
DEFAULT_MANUAL_BANTIME);
auto connman = std::make_unique<CConnman>(config, 0x1337, 0x1337);
auto peerLogic = std::make_unique<PeerLogicValidation>(
connman.get(), banman.get(), scheduler, false);
banman->ClearAll();
// because 11 is my favorite number.
gArgs.ForceSetArg("-banscore", "111");
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1,
CAddress(), "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
peerLogic->InitializeNode(config, &dummyNode1);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
{
LOCK(cs_main);
Misbehaving(dummyNode1.GetId(), 100, "");
}
{
LOCK2(cs_main, dummyNode1.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode1, interruptDummy));
}
BOOST_CHECK(!banman->IsDiscouraged(addr1));
{
LOCK(cs_main);
Misbehaving(dummyNode1.GetId(), 10, "");
}
{
LOCK2(cs_main, dummyNode1.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode1, interruptDummy));
}
BOOST_CHECK(!banman->IsDiscouraged(addr1));
{
LOCK(cs_main);
Misbehaving(dummyNode1.GetId(), 1, "");
}
{
LOCK2(cs_main, dummyNode1.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode1, interruptDummy));
}
BOOST_CHECK(banman->IsDiscouraged(addr1));
gArgs.ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));
bool dummy;
peerLogic->FinalizeNode(config, dummyNode1.GetId(), dummy);
}
BOOST_AUTO_TEST_CASE(DoS_bantime) {
const Config &config = GetConfig();
std::atomic<bool> interruptDummy(false);
auto banman = std::make_unique<BanMan>(GetDataDir() / "banlist.dat",
config.GetChainParams(), nullptr,
DEFAULT_MANUAL_BANTIME);
auto connman = std::make_unique<CConnman>(config, 0x1337, 0x1337);
auto peerLogic = std::make_unique<PeerLogicValidation>(
connman.get(), banman.get(), scheduler, false);
banman->ClearAll();
int64_t nStartTime = GetTime();
// Overrides future calls to GetTime()
SetMockTime(nStartTime);
CAddress addr(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4,
CAddress(), "", true);
dummyNode.SetSendVersion(PROTOCOL_VERSION);
peerLogic->InitializeNode(config, &dummyNode);
dummyNode.nVersion = 1;
dummyNode.fSuccessfullyConnected = true;
{
LOCK(cs_main);
Misbehaving(dummyNode.GetId(), 100, "");
}
{
LOCK2(cs_main, dummyNode.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(config, &dummyNode, interruptDummy));
}
const CNetAddr bannedAddr{ip(0xd0e0f002)};
banman->Ban(bannedAddr);
BOOST_CHECK(banman->IsBanned(bannedAddr));
BOOST_CHECK(banman->IsDiscouraged(addr));
BOOST_CHECK(!banman->IsBanned(addr));
SetMockTime(nStartTime + 60 * 60);
BOOST_CHECK(banman->IsDiscouraged(addr));
BOOST_CHECK(banman->IsBanned(bannedAddr));
SetMockTime(nStartTime + 60 * 60 * 24 + 1);
// banning should expire
BOOST_CHECK(!banman->IsBanned(bannedAddr));
// discouragement never expires ...
BOOST_CHECK(banman->IsDiscouraged(addr));
// ... unless we clear the discourage bloom filter
banman->ClearDiscouraged();
BOOST_CHECK(!banman->IsDiscouraged(addr));
bool dummy;
peerLogic->FinalizeNode(config, dummyNode.GetId(), dummy);
}
static CNetAddr GenAddress() {
// deterministic hasher to always generate the same set of addrs
static CSipHasher hasher{0xfeedbeeff00d1234, 0x9001231231471231};
static uint64_t last{0x123456789abcdef7};
uint64_t lo, hi;
last = lo = hasher.Write(last).Finalize();
last = hi = hasher.Write(last).Finalize();
static const auto ip6 = [](uint64_t w1, uint64_t w2) {
struct in6_addr s;
static_assert(sizeof(s) == sizeof(uint64_t) * 2, "ipv6 address should be 128 bits");
uint8_t *buf = reinterpret_cast<uint8_t *>(&s);
std::memcpy(buf, &w1, sizeof(w1));
std::memcpy(buf + sizeof(w1), &w2, sizeof(w2));
return CNetAddr{s};
};
return ip6(lo, hi);
}
BOOST_AUTO_TEST_CASE(DoS_DiscourageRolling) {
const Config &config = GetConfig();
auto banman = std::make_unique<BanMan>(GetDataDir() / "banlist.dat",
config.GetChainParams(), nullptr,
DEFAULT_MANUAL_BANTIME);
banman->ClearAll();
constexpr int FilterSize = int(BanMan::DiscourageFilterSize());
constexpr int NGen = FilterSize * 1.5 + 1;
std::vector<CNetAddr> addrs;
addrs.reserve(NGen);
for (int i = 0; i < NGen; ++i) {
auto addr = GenAddress();
banman->Discourage(addr);
// make sure discouragement at least immediately works
BOOST_CHECK(banman->IsDiscouraged(addr));
addrs.push_back(addr);
}
// check the rolling properly of the filter in that it "forgets" older discouraged addresses after
// its filter size is exhausted.
BOOST_CHECK(!banman->IsDiscouraged(addrs.front()));
// check that the most recent additions are still all discouraged (but not banned)
int i = 0;
for (auto rit = addrs.rbegin(); rit != addrs.rend() && i < FilterSize; ++i, ++rit) {
BOOST_CHECK(banman->IsDiscouraged(*rit));
BOOST_CHECK(!banman->IsBanned(*rit));
}
// next, clear the filter and check nothing is Discouraged anymore
banman->ClearDiscouraged();
for (const auto &addr : addrs) {
BOOST_CHECK(!banman->IsDiscouraged(addr));
}
}
static CTransactionRef RandomOrphan() {
LOCK2(cs_main, internal::g_cs_orphans);
auto it = internal::mapOrphanTransactions.lower_bound(TxId{InsecureRand256()});
if (it == internal::mapOrphanTransactions.end()) {
it = internal::mapOrphanTransactions.begin();
}
return it->second.tx;
}
static void CheckMapOrphanTxByPrevSanity() {
LOCK(internal::g_cs_orphans);
const internal::MapOrphanTransactions &m = internal::mapOrphanTransactions;
const internal::MapOrphanTransactionsByPrev &mp = internal::mapOrphanTransactionsByPrev;
// every entry in mp must be a valid iterator in m, and there must be no empty sets in mp
for (const auto & [outpt, set] : mp) {
BOOST_CHECK(!set.empty());
for (const auto &it : set) {
const auto mit = m.find(it->first);
BOOST_CHECK(mit != m.end()); // must exist
BOOST_CHECK(it == mit); // must be the same iterator in m
BOOST_CHECK(it->first == it->second.tx->GetId()); // check that the txid is the same (paranoia)
}
}
// every tx in m must have an entry in mp for each of its CTxIns
auto &m_nonconst = internal::mapOrphanTransactions; // we need a non-const iterator for below
for (auto it = m_nonconst.begin(); it != m_nonconst.end(); ++it) {
const auto & [txid, orphantx] = *it;
for (const auto &txin : orphantx.tx->vin) {
const auto it2 = mp.find(txin.prevout);
BOOST_CHECK(it2 != mp.end());
// sanity check the other way -- entry must exist in set, and it must be this iterator
BOOST_CHECK(it2->second.count(it) == 1); // count here only works with non-const `it`
}
}
}
BOOST_AUTO_TEST_SUITE_END()