Skip to content

Commit fef65c4

Browse files
committed
Merge #11113: [net] Ignore getheaders requests for very old side blocks
eff4bd8 [test] P2P functional test for certain fingerprinting protections (Jim Posen) a2be3b6 [net] Ignore getheaders requests for very old side blocks (Jim Posen) Pull request description: Sending a getheaders message with an empty locator and a stop hash is a request for a single header by hash. The node will respond with headers for blocks not in the main chain as well as those in the main chain. To avoid fingerprinting, the node should, however, ignore requests for headers on side branches that are too old. This replicates the logic that currently exists for `getdata` requests for blocks. Tree-SHA512: e04ef61e2b73945be6ec5977b3c5680b6dc3667246f8bfb67afae1ecaba900c0b49b18bbbb74869f7a37ef70b6ed99e78ebe0ea0a1569369fad9e447d720ffc4
2 parents 0e3a411 + eff4bd8 commit fef65c4

File tree

4 files changed

+189
-11
lines changed

4 files changed

+189
-11
lines changed

src/net_processing.cpp

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,14 @@ static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUAR
6161

6262
static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
6363

64+
/// Age after which a stale block will no longer be served if requested as
65+
/// protection against fingerprinting. Set to one month, denominated in seconds.
66+
static const int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
67+
68+
/// Age after which a block is considered historical for purposes of rate
69+
/// limiting block relay. Set to one week, denominated in seconds.
70+
static const int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
71+
6472
// Internal stuff
6573
namespace {
6674
/** Number of nodes with fSyncStarted. */
@@ -706,6 +714,17 @@ void Misbehaving(NodeId pnode, int howmuch)
706714
// blockchain -> download logic notification
707715
//
708716

717+
// To prevent fingerprinting attacks, only send blocks/headers outside of the
718+
// active chain if they are no more than a month older (both in time, and in
719+
// best equivalent proof of work) than the best header chain we know about.
720+
static bool StaleBlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Params& consensusParams)
721+
{
722+
AssertLockHeld(cs_main);
723+
return (pindexBestHeader != nullptr) &&
724+
(pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
725+
(GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT);
726+
}
727+
709728
PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn) : connman(connmanIn) {
710729
// Initialize global variables that cannot be constructed at startup.
711730
recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
@@ -983,22 +1002,16 @@ void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParam
9831002
if (chainActive.Contains(mi->second)) {
9841003
send = true;
9851004
} else {
986-
static const int nOneMonth = 30 * 24 * 60 * 60;
987-
// To prevent fingerprinting attacks, only send blocks outside of the active
988-
// chain if they are valid, and no more than a month older (both in time, and in
989-
// best equivalent proof of work) than the best header chain we know about.
990-
send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) &&
991-
(pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
992-
(GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth);
1005+
send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1006+
StaleBlockRequestAllowed(mi->second, consensusParams);
9931007
if (!send) {
9941008
LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
9951009
}
9961010
}
9971011
}
9981012
// disconnect node in case we have reached the outbound limit for serving historical blocks
9991013
// never disconnect whitelisted nodes
1000-
static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
1001-
if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
1014+
if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
10021015
{
10031016
LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
10041017

@@ -1723,6 +1736,12 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
17231736
if (mi == mapBlockIndex.end())
17241737
return true;
17251738
pindex = (*mi).second;
1739+
1740+
if (!chainActive.Contains(pindex) &&
1741+
!StaleBlockRequestAllowed(pindex, chainparams.GetConsensus())) {
1742+
LogPrintf("%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId());
1743+
return true;
1744+
}
17261745
}
17271746
else
17281747
{

test/functional/p2p-fingerprint.py

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2017 The Bitcoin Core developers
3+
# Distributed under the MIT software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
"""Test various fingerprinting protections.
6+
7+
If an stale block more than a month old or its header are requested by a peer,
8+
the node should pretend that it does not have it to avoid fingerprinting.
9+
"""
10+
11+
import time
12+
13+
from test_framework.blocktools import (create_block, create_coinbase)
14+
from test_framework.mininode import (
15+
CInv,
16+
NetworkThread,
17+
NodeConn,
18+
NodeConnCB,
19+
msg_headers,
20+
msg_block,
21+
msg_getdata,
22+
msg_getheaders,
23+
wait_until,
24+
)
25+
from test_framework.test_framework import BitcoinTestFramework
26+
from test_framework.util import (
27+
assert_equal,
28+
p2p_port,
29+
)
30+
31+
class P2PFingerprintTest(BitcoinTestFramework):
32+
def set_test_params(self):
33+
self.setup_clean_chain = True
34+
self.num_nodes = 1
35+
36+
# Build a chain of blocks on top of given one
37+
def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time):
38+
blocks = []
39+
for _ in range(nblocks):
40+
coinbase = create_coinbase(prev_height + 1)
41+
block_time = prev_median_time + 1
42+
block = create_block(int(prev_hash, 16), coinbase, block_time)
43+
block.solve()
44+
45+
blocks.append(block)
46+
prev_hash = block.hash
47+
prev_height += 1
48+
prev_median_time = block_time
49+
return blocks
50+
51+
# Send a getdata request for a given block hash
52+
def send_block_request(self, block_hash, node):
53+
msg = msg_getdata()
54+
msg.inv.append(CInv(2, block_hash)) # 2 == "Block"
55+
node.send_message(msg)
56+
57+
# Send a getheaders request for a given single block hash
58+
def send_header_request(self, block_hash, node):
59+
msg = msg_getheaders()
60+
msg.hashstop = block_hash
61+
node.send_message(msg)
62+
63+
# Check whether last block received from node has a given hash
64+
def last_block_equals(self, expected_hash, node):
65+
block_msg = node.last_message.get("block")
66+
return block_msg and block_msg.block.rehash() == expected_hash
67+
68+
# Check whether last block header received from node has a given hash
69+
def last_header_equals(self, expected_hash, node):
70+
headers_msg = node.last_message.get("headers")
71+
return (headers_msg and
72+
headers_msg.headers and
73+
headers_msg.headers[0].rehash() == expected_hash)
74+
75+
# Checks that stale blocks timestamped more than a month ago are not served
76+
# by the node while recent stale blocks and old active chain blocks are.
77+
# This does not currently test that stale blocks timestamped within the
78+
# last month but that have over a month's worth of work are also withheld.
79+
def run_test(self):
80+
node0 = NodeConnCB()
81+
82+
connections = []
83+
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], node0))
84+
node0.add_connection(connections[0])
85+
86+
NetworkThread().start()
87+
node0.wait_for_verack()
88+
89+
# Set node time to 60 days ago
90+
self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60)
91+
92+
# Generating a chain of 10 blocks
93+
block_hashes = self.nodes[0].generate(nblocks=10)
94+
95+
# Create longer chain starting 2 blocks before current tip
96+
height = len(block_hashes) - 2
97+
block_hash = block_hashes[height - 1]
98+
block_time = self.nodes[0].getblockheader(block_hash)["mediantime"] + 1
99+
new_blocks = self.build_chain(5, block_hash, height, block_time)
100+
101+
# Force reorg to a longer chain
102+
node0.send_message(msg_headers(new_blocks))
103+
node0.wait_for_getdata()
104+
for block in new_blocks:
105+
node0.send_and_ping(msg_block(block))
106+
107+
# Check that reorg succeeded
108+
assert_equal(self.nodes[0].getblockcount(), 13)
109+
110+
stale_hash = int(block_hashes[-1], 16)
111+
112+
# Check that getdata request for stale block succeeds
113+
self.send_block_request(stale_hash, node0)
114+
test_function = lambda: self.last_block_equals(stale_hash, node0)
115+
wait_until(test_function, timeout=3)
116+
117+
# Check that getheader request for stale block header succeeds
118+
self.send_header_request(stale_hash, node0)
119+
test_function = lambda: self.last_header_equals(stale_hash, node0)
120+
wait_until(test_function, timeout=3)
121+
122+
# Longest chain is extended so stale is much older than chain tip
123+
self.nodes[0].setmocktime(0)
124+
tip = self.nodes[0].generate(nblocks=1)[0]
125+
assert_equal(self.nodes[0].getblockcount(), 14)
126+
127+
# Send getdata & getheaders to refresh last received getheader message
128+
block_hash = int(tip, 16)
129+
self.send_block_request(block_hash, node0)
130+
self.send_header_request(block_hash, node0)
131+
node0.sync_with_ping()
132+
133+
# Request for very old stale block should now fail
134+
self.send_block_request(stale_hash, node0)
135+
time.sleep(3)
136+
assert not self.last_block_equals(stale_hash, node0)
137+
138+
# Request for very old stale block header should now fail
139+
self.send_header_request(stale_hash, node0)
140+
time.sleep(3)
141+
assert not self.last_header_equals(stale_hash, node0)
142+
143+
# Verify we can fetch very old blocks and headers on the active chain
144+
block_hash = int(block_hashes[2], 16)
145+
self.send_block_request(block_hash, node0)
146+
self.send_header_request(block_hash, node0)
147+
node0.sync_with_ping()
148+
149+
self.send_block_request(block_hash, node0)
150+
test_function = lambda: self.last_block_equals(block_hash, node0)
151+
wait_until(test_function, timeout=3)
152+
153+
self.send_header_request(block_hash, node0)
154+
test_function = lambda: self.last_header_equals(block_hash, node0)
155+
wait_until(test_function, timeout=3)
156+
157+
if __name__ == '__main__':
158+
P2PFingerprintTest().main()

test/functional/test_framework/mininode.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1310,8 +1310,8 @@ def __repr__(self):
13101310
class msg_headers(object):
13111311
command = b"headers"
13121312

1313-
def __init__(self):
1314-
self.headers = []
1313+
def __init__(self, headers=None):
1314+
self.headers = headers if headers is not None else []
13151315

13161316
def deserialize(self, f):
13171317
# comment in bitcoind indicates these should be deserialized as blocks

test/functional/test_runner.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@
123123
'uptime.py',
124124
'resendwallettransactions.py',
125125
'minchainwork.py',
126+
'p2p-fingerprint.py',
126127
]
127128

128129
EXTENDED_SCRIPTS = [

0 commit comments

Comments
 (0)