Skip to content

Commit dede9eb

Browse files
committed
Merge #20197: p2p: protect onions in AttemptToEvictConnection(), add eviction protection test coverage
0cca08a Add unit test coverage for our onion peer eviction protection (Jon Atack) caa21f5 Protect onion+localhost peers in ProtectEvictionCandidatesByRatio() (Jon Atack) 8f1a53e Use EraseLastKElements() throughout SelectNodeToEvict() (Jon Atack) 8b1e156 Add m_inbound_onion to AttemptToEvictConnection() (Jon Atack) 72e30e8 Add unit tests for ProtectEvictionCandidatesByRatio() (Jon Atack) ca63b53 Use std::unordered_set instead of std::vector in IsEvicted() (Jon Atack) 41f84d5 Move peer eviction tests to a separate test file (Jon Atack) f126cbd Extract ProtectEvictionCandidatesByRatio from SelectNodeToEvict (Jon Atack) Pull request description: Now that #19991 and #20210 have been merged, we can determine inbound onion peers using `CNode::m_inbound_onion` and add it to the localhost peers protection in `AttemptToEvictConnection`, which was added in #19670 to address issue #19500. Update 28 February 2021: I've updated this to follow gmaxwell's suggestion in bitcoin/bitcoin#20197 (comment). This branch now protects up to 1/4 onion peers (connected via our tor control service), if any, sorted by longest uptime. If any (or all) onion slots remain after that operation, they are then allocated to protect localhost peers, or a minimum of 2 localhost peers in the case that no onion slots remain and 2 or more onion peers were protected, sorted as before by longest uptime. This patch also adds test coverage for the longest uptime, localhost, and onion peer eviction protection logic to build on the welcome initial unit testing of #20477. Suggest reviewing the commits that move code with `colorMoved = dimmed-zebra` and `colorMovedWs = allow-indentation-change`. Closes #11537. ACKs for top commit: laanwj: Code review ACK 0cca08a vasild: ACK 0cca08a Tree-SHA512: 2f5a63f942acaae7882920fc61f0185dcd51da85e5b736df9d1fc72343726dd17da740e02f30fa5dc5eb3b2d8345707aed96031bec143d48a2497a610aa19abd
2 parents 1999baa + 0cca08a commit dede9eb

File tree

6 files changed

+439
-168
lines changed

6 files changed

+439
-168
lines changed

src/Makefile.test.include

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ BITCOIN_TESTS =\
101101
test/merkleblock_tests.cpp \
102102
test/miner_tests.cpp \
103103
test/multisig_tests.cpp \
104+
test/net_peer_eviction_tests.cpp \
104105
test/net_tests.cpp \
105106
test/netbase_tests.cpp \
106107
test/pmt_tests.cpp \

src/net.cpp

Lines changed: 57 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,12 @@ static bool CompareLocalHostTimeConnected(const NodeEvictionCandidate &a, const
840840
return a.nTimeConnected > b.nTimeConnected;
841841
}
842842

843+
static bool CompareOnionTimeConnected(const NodeEvictionCandidate& a, const NodeEvictionCandidate& b)
844+
{
845+
if (a.m_is_onion != b.m_is_onion) return b.m_is_onion;
846+
return a.nTimeConnected > b.nTimeConnected;
847+
}
848+
843849
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) {
844850
return a.nKeyedNetGroup < b.nKeyedNetGroup;
845851
}
@@ -870,13 +876,51 @@ static bool CompareNodeBlockRelayOnlyTime(const NodeEvictionCandidate &a, const
870876
return a.nTimeConnected > b.nTimeConnected;
871877
}
872878

873-
//! Sort an array by the specified comparator, then erase the last K elements.
874-
template<typename T, typename Comparator>
875-
static void EraseLastKElements(std::vector<T> &elements, Comparator comparator, size_t k)
879+
//! Sort an array by the specified comparator, then erase the last K elements where predicate is true.
880+
template <typename T, typename Comparator>
881+
static void EraseLastKElements(
882+
std::vector<T>& elements, Comparator comparator, size_t k,
883+
std::function<bool(const NodeEvictionCandidate&)> predicate = [](const NodeEvictionCandidate& n) { return true; })
876884
{
877885
std::sort(elements.begin(), elements.end(), comparator);
878886
size_t eraseSize = std::min(k, elements.size());
879-
elements.erase(elements.end() - eraseSize, elements.end());
887+
elements.erase(std::remove_if(elements.end() - eraseSize, elements.end(), predicate), elements.end());
888+
}
889+
890+
void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& vEvictionCandidates)
891+
{
892+
// Protect the half of the remaining nodes which have been connected the longest.
893+
// This replicates the non-eviction implicit behavior, and precludes attacks that start later.
894+
// To favorise the diversity of our peer connections, reserve up to (half + 2) of
895+
// these protected spots for onion and localhost peers, if any, even if they're not
896+
// longest uptime overall. This helps protect tor peers, which tend to be otherwise
897+
// disadvantaged under our eviction criteria.
898+
const size_t initial_size = vEvictionCandidates.size();
899+
size_t total_protect_size = initial_size / 2;
900+
const size_t onion_protect_size = total_protect_size / 2;
901+
902+
if (onion_protect_size) {
903+
// Pick out up to 1/4 peers connected via our onion service, sorted by longest uptime.
904+
EraseLastKElements(vEvictionCandidates, CompareOnionTimeConnected, onion_protect_size,
905+
[](const NodeEvictionCandidate& n) { return n.m_is_onion; });
906+
}
907+
908+
const size_t localhost_min_protect_size{2};
909+
if (onion_protect_size >= localhost_min_protect_size) {
910+
// Allocate any remaining slots of the 1/4, or minimum 2 additional slots,
911+
// to localhost peers, sorted by longest uptime, as manually configured
912+
// hidden services not using `-bind=addr[:port]=onion` will not be detected
913+
// as inbound onion connections.
914+
const size_t remaining_tor_slots{onion_protect_size - (initial_size - vEvictionCandidates.size())};
915+
const size_t localhost_protect_size{std::max(remaining_tor_slots, localhost_min_protect_size)};
916+
EraseLastKElements(vEvictionCandidates, CompareLocalHostTimeConnected, localhost_protect_size,
917+
[](const NodeEvictionCandidate& n) { return n.m_is_local; });
918+
}
919+
920+
// Calculate how many we removed, and update our total number of peers that
921+
// we want to protect based on uptime accordingly.
922+
total_protect_size -= initial_size - vEvictionCandidates.size();
923+
EraseLastKElements(vEvictionCandidates, ReverseCompareNodeTimeConnected, total_protect_size);
880924
}
881925

882926
[[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates)
@@ -893,30 +937,17 @@ static void EraseLastKElements(std::vector<T> &elements, Comparator comparator,
893937
// An attacker cannot manipulate this metric without performing useful work.
894938
EraseLastKElements(vEvictionCandidates, CompareNodeTXTime, 4);
895939
// Protect up to 8 non-tx-relay peers that have sent us novel blocks.
896-
std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeBlockRelayOnlyTime);
897-
size_t erase_size = std::min(size_t(8), vEvictionCandidates.size());
898-
vEvictionCandidates.erase(std::remove_if(vEvictionCandidates.end() - erase_size, vEvictionCandidates.end(), [](NodeEvictionCandidate const &n) { return !n.fRelayTxes && n.fRelevantServices; }), vEvictionCandidates.end());
940+
const size_t erase_size = std::min(size_t(8), vEvictionCandidates.size());
941+
EraseLastKElements(vEvictionCandidates, CompareNodeBlockRelayOnlyTime, erase_size,
942+
[](const NodeEvictionCandidate& n) { return !n.fRelayTxes && n.fRelevantServices; });
899943

900944
// Protect 4 nodes that most recently sent us novel blocks.
901945
// An attacker cannot manipulate this metric without performing useful work.
902946
EraseLastKElements(vEvictionCandidates, CompareNodeBlockTime, 4);
903947

904-
// Protect the half of the remaining nodes which have been connected the longest.
905-
// This replicates the non-eviction implicit behavior, and precludes attacks that start later.
906-
// Reserve half of these protected spots for localhost peers, even if
907-
// they're not longest-uptime overall. This helps protect tor peers, which
908-
// tend to be otherwise disadvantaged under our eviction criteria.
909-
size_t initial_size = vEvictionCandidates.size();
910-
size_t total_protect_size = initial_size / 2;
911-
912-
// Pick out up to 1/4 peers that are localhost, sorted by longest uptime.
913-
std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareLocalHostTimeConnected);
914-
size_t local_erase_size = total_protect_size / 2;
915-
vEvictionCandidates.erase(std::remove_if(vEvictionCandidates.end() - local_erase_size, vEvictionCandidates.end(), [](NodeEvictionCandidate const &n) { return n.m_is_local; }), vEvictionCandidates.end());
916-
// Calculate how many we removed, and update our total number of peers that
917-
// we want to protect based on uptime accordingly.
918-
total_protect_size -= initial_size - vEvictionCandidates.size();
919-
EraseLastKElements(vEvictionCandidates, ReverseCompareNodeTimeConnected, total_protect_size);
948+
// Protect some of the remaining eviction candidates by ratios of desirable
949+
// or disadvantaged characteristics.
950+
ProtectEvictionCandidatesByRatio(vEvictionCandidates);
920951

921952
if (vEvictionCandidates.empty()) return std::nullopt;
922953

@@ -937,7 +968,7 @@ static void EraseLastKElements(std::vector<T> &elements, Comparator comparator,
937968
for (const NodeEvictionCandidate &node : vEvictionCandidates) {
938969
std::vector<NodeEvictionCandidate> &group = mapNetGroupNodes[node.nKeyedNetGroup];
939970
group.push_back(node);
940-
int64_t grouptime = group[0].nTimeConnected;
971+
const int64_t grouptime = group[0].nTimeConnected;
941972

942973
if (group.size() > nMostConnections || (group.size() == nMostConnections && grouptime > nMostConnectionsTime)) {
943974
nMostConnections = group.size();
@@ -985,7 +1016,8 @@ bool CConnman::AttemptToEvictConnection()
9851016
node->nLastBlockTime, node->nLastTXTime,
9861017
HasAllDesirableServiceFlags(node->nServices),
9871018
peer_relay_txes, peer_filter_not_null, node->nKeyedNetGroup,
988-
node->m_prefer_evict, node->addr.IsLocal()};
1019+
node->m_prefer_evict, node->addr.IsLocal(),
1020+
node->m_inbound_onion};
9891021
vEvictionCandidates.push_back(candidate);
9901022
}
9911023
}

src/net.h

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,7 @@ class CNode
425425

426426
std::atomic<int64_t> nLastSend{0};
427427
std::atomic<int64_t> nLastRecv{0};
428+
//! Unix epoch time at peer connection, in seconds.
428429
const int64_t nTimeConnected;
429430
std::atomic<int64_t> nTimeOffset{0};
430431
// Address of this peer
@@ -1278,8 +1279,39 @@ struct NodeEvictionCandidate
12781279
uint64_t nKeyedNetGroup;
12791280
bool prefer_evict;
12801281
bool m_is_local;
1282+
bool m_is_onion;
12811283
};
12821284

1285+
/**
1286+
* Select an inbound peer to evict after filtering out (protecting) peers having
1287+
* distinct, difficult-to-forge characteristics. The protection logic picks out
1288+
* fixed numbers of desirable peers per various criteria, followed by (mostly)
1289+
* ratios of desirable or disadvantaged peers. If any eviction candidates
1290+
* remain, the selection logic chooses a peer to evict.
1291+
*/
12831292
[[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates);
12841293

1294+
/** Protect desirable or disadvantaged inbound peers from eviction by ratio.
1295+
*
1296+
* This function protects half of the peers which have been connected the
1297+
* longest, to replicate the non-eviction implicit behavior and preclude attacks
1298+
* that start later.
1299+
*
1300+
* Half of these protected spots (1/4 of the total) are reserved for onion peers
1301+
* connected via our tor control service, if any, sorted by longest uptime, even
1302+
* if they're not longest uptime overall. Any remaining slots of the 1/4 are
1303+
* then allocated to protect localhost peers, if any (or up to 2 localhost peers
1304+
* if no slots remain and 2 or more onion peers were protected), sorted by
1305+
* longest uptime, as manually configured hidden services not using
1306+
* `-bind=addr[:port]=onion` will not be detected as inbound onion connections.
1307+
*
1308+
* This helps protect onion peers, which tend to be otherwise disadvantaged
1309+
* under our eviction criteria for their higher min ping times relative to IPv4
1310+
* and IPv6 peers, and favorise the diversity of peer connections.
1311+
*
1312+
* This function was extracted from SelectNodeToEvict() to be able to test the
1313+
* ratio-based protection logic deterministically.
1314+
*/
1315+
void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& vEvictionCandidates);
1316+
12851317
#endif // BITCOIN_NET_H

src/test/fuzz/node_eviction.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ FUZZ_TARGET(node_eviction)
3131
/* nKeyedNetGroup */ fuzzed_data_provider.ConsumeIntegral<uint64_t>(),
3232
/* prefer_evict */ fuzzed_data_provider.ConsumeBool(),
3333
/* m_is_local */ fuzzed_data_provider.ConsumeBool(),
34+
/* m_is_onion */ fuzzed_data_provider.ConsumeBool(),
3435
});
3536
}
3637
// Make a copy since eviction_candidates may be in some valid but otherwise

0 commit comments

Comments
 (0)