Skip to content

Commit c51c694

Browse files
committed
Merge bitcoin/bitcoin#29431: test/BIP324: disconnection scenarios during v2 handshake
c9dacd9 test: Check that non empty version packet is ignored and no disconnection happens (stratospher) 997cc00 test: Check that disconnection happens when AAD isn't filled (stratospher) b5e6238 test: Check that disconnection happens when garbage sent/received are different (stratospher) ad1482d test: Check that disconnection happens when wrong garbage terminator is sent (stratospher) e351576 test: Check that disconnection happens when >4095 garbage bytes is sent (stratospher) e075fd1 test: Introduce test types and modify v2 handshake function accordingly (stratospher) 7d07daa log: Add V2 handshake timeout (stratospher) d4a1da8 test: Make global TRANSPORT_VERSION variable an instance variable (stratospher) c642b08 test: Log when the garbage is actually sent to transport layer (stratospher) 86cca2c test: Support disconnect waiting for add_p2p_connection (stratospher) bf9669a test: Rename early key response test and move random_bitflip to util (stratospher) Pull request description: Add tests for the following v2 handshake scenarios: 1. Disconnection happens when > `MAX_GARBAGE_LEN` bytes garbage is sent 2. Disconnection happens when incorrect garbage terminator is sent 3. Disconnection happens when garbage bytes are tampered with 4. Disconnection happens when AAD of first encrypted packet after the garbage terminator is not filled 5. bitcoind ignores non-empty version packet and no disconnection happens All these tests require a modified v2 P2P class (different from `EncryptedP2PState` used in `v2_p2p.py`) to implement our custom handshake behaviour based on different scenarios and have been kept in a single test file (`test/functional/p2p_v2_misbehaving.py`). Shifted the test in `test/functional/p2p_v2_earlykeyresponse.py` which is of the same pattern to this file too. ACKs for top commit: achow101: ACK c9dacd9 mzumsande: ACK c9dacd9 theStack: Code-review ACK c9dacd9 Tree-SHA512: 90df81f0c7f4ecf0a47762d290a618ded92cde9f83d3ef3cc70e1b005ecb16125ec39a9d80ce95f99e695d29abd63443240cb5490aa57c5bc8fa2e52149a0672
2 parents 5239e93 + c9dacd9 commit c51c694

File tree

9 files changed

+200
-105
lines changed

9 files changed

+200
-105
lines changed

src/net.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1983,7 +1983,11 @@ bool CConnman::InactivityCheck(const CNode& node) const
19831983
}
19841984

19851985
if (!node.fSuccessfullyConnected) {
1986-
LogPrint(BCLog::NET, "version handshake timeout peer=%d\n", node.GetId());
1986+
if (node.m_transport->GetInfo().transport_type == TransportProtocolType::DETECTING) {
1987+
LogPrint(BCLog::NET, "V2 handshake timeout peer=%d\n", node.GetId());
1988+
} else {
1989+
LogPrint(BCLog::NET, "version handshake timeout peer=%d\n", node.GetId());
1990+
}
19871991
return true;
19881992
}
19891993

test/functional/p2p_v2_earlykeyresponse.py

Lines changed: 0 additions & 89 deletions
This file was deleted.

test/functional/p2p_v2_misbehaving.py

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2022 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+
6+
import random
7+
from enum import Enum
8+
9+
from test_framework.messages import MAGIC_BYTES
10+
from test_framework.p2p import P2PInterface
11+
from test_framework.test_framework import BitcoinTestFramework
12+
from test_framework.util import random_bitflip
13+
from test_framework.v2_p2p import (
14+
EncryptedP2PState,
15+
MAX_GARBAGE_LEN,
16+
)
17+
18+
19+
class TestType(Enum):
20+
""" Scenarios to be tested:
21+
22+
1. EARLY_KEY_RESPONSE - The responder needs to wait until one byte is received which does not match the 16 bytes
23+
consisting of network magic followed by "version\x00\x00\x00\x00\x00" before sending out its ellswift + garbage bytes
24+
2. EXCESS_GARBAGE - Disconnection happens when > MAX_GARBAGE_LEN bytes garbage is sent
25+
3. WRONG_GARBAGE_TERMINATOR - Disconnection happens when incorrect garbage terminator is sent
26+
4. WRONG_GARBAGE - Disconnection happens when garbage bytes that is sent is different from what the peer receives
27+
5. SEND_NO_AAD - Disconnection happens when AAD of first encrypted packet after the garbage terminator is not filled
28+
6. SEND_NON_EMPTY_VERSION_PACKET - non-empty version packet is simply ignored
29+
"""
30+
EARLY_KEY_RESPONSE = 0
31+
EXCESS_GARBAGE = 1
32+
WRONG_GARBAGE_TERMINATOR = 2
33+
WRONG_GARBAGE = 3
34+
SEND_NO_AAD = 4
35+
SEND_NON_EMPTY_VERSION_PACKET = 5
36+
37+
38+
class EarlyKeyResponseState(EncryptedP2PState):
39+
""" Modify v2 P2P protocol functions for testing EARLY_KEY_RESPONSE scenario"""
40+
def __init__(self, initiating, net):
41+
super().__init__(initiating=initiating, net=net)
42+
self.can_data_be_received = False # variable used to assert if data is received on recvbuf.
43+
44+
def initiate_v2_handshake(self):
45+
"""Send ellswift and garbage bytes in 2 parts when TestType = (EARLY_KEY_RESPONSE)"""
46+
self.generate_keypair_and_garbage()
47+
return b""
48+
49+
50+
class ExcessGarbageState(EncryptedP2PState):
51+
"""Generate > MAX_GARBAGE_LEN garbage bytes"""
52+
def generate_keypair_and_garbage(self):
53+
garbage_len = MAX_GARBAGE_LEN + random.randrange(1, MAX_GARBAGE_LEN + 1)
54+
return super().generate_keypair_and_garbage(garbage_len)
55+
56+
57+
class WrongGarbageTerminatorState(EncryptedP2PState):
58+
"""Add option for sending wrong garbage terminator"""
59+
def generate_keypair_and_garbage(self):
60+
garbage_len = random.randrange(MAX_GARBAGE_LEN//2)
61+
return super().generate_keypair_and_garbage(garbage_len)
62+
63+
def complete_handshake(self, response):
64+
length, handshake_bytes = super().complete_handshake(response)
65+
# first 16 bytes returned by complete_handshake() is the garbage terminator
66+
wrong_garbage_terminator = random_bitflip(handshake_bytes[:16])
67+
return length, wrong_garbage_terminator + handshake_bytes[16:]
68+
69+
70+
class WrongGarbageState(EncryptedP2PState):
71+
"""Generate tampered garbage bytes"""
72+
def generate_keypair_and_garbage(self):
73+
garbage_len = random.randrange(1, MAX_GARBAGE_LEN)
74+
ellswift_garbage_bytes = super().generate_keypair_and_garbage(garbage_len)
75+
# assume that garbage bytes sent to TestNode were tampered with
76+
return ellswift_garbage_bytes[:64] + random_bitflip(ellswift_garbage_bytes[64:])
77+
78+
79+
class NoAADState(EncryptedP2PState):
80+
"""Add option for not filling first encrypted packet after garbage terminator with AAD"""
81+
def generate_keypair_and_garbage(self):
82+
garbage_len = random.randrange(1, MAX_GARBAGE_LEN)
83+
return super().generate_keypair_and_garbage(garbage_len)
84+
85+
def complete_handshake(self, response):
86+
self.sent_garbage = b'' # do not authenticate the garbage which is sent
87+
return super().complete_handshake(response)
88+
89+
90+
class NonEmptyVersionPacketState(EncryptedP2PState):
91+
""""Add option for sending non-empty transport version packet."""
92+
def complete_handshake(self, response):
93+
self.transport_version = random.randbytes(5)
94+
return super().complete_handshake(response)
95+
96+
97+
class MisbehavingV2Peer(P2PInterface):
98+
"""Custom implementation of P2PInterface which uses modified v2 P2P protocol functions for testing purposes."""
99+
def __init__(self, test_type):
100+
super().__init__()
101+
self.test_type = test_type
102+
103+
def connection_made(self, transport):
104+
if self.test_type == TestType.EARLY_KEY_RESPONSE:
105+
self.v2_state = EarlyKeyResponseState(initiating=True, net='regtest')
106+
elif self.test_type == TestType.EXCESS_GARBAGE:
107+
self.v2_state = ExcessGarbageState(initiating=True, net='regtest')
108+
elif self.test_type == TestType.WRONG_GARBAGE_TERMINATOR:
109+
self.v2_state = WrongGarbageTerminatorState(initiating=True, net='regtest')
110+
elif self.test_type == TestType.WRONG_GARBAGE:
111+
self.v2_state = WrongGarbageState(initiating=True, net='regtest')
112+
elif self.test_type == TestType.SEND_NO_AAD:
113+
self.v2_state = NoAADState(initiating=True, net='regtest')
114+
elif TestType.SEND_NON_EMPTY_VERSION_PACKET:
115+
self.v2_state = NonEmptyVersionPacketState(initiating=True, net='regtest')
116+
super().connection_made(transport)
117+
118+
def data_received(self, t):
119+
if self.test_type == TestType.EARLY_KEY_RESPONSE:
120+
# check that data can be received on recvbuf only when mismatch from V1_PREFIX happens
121+
assert self.v2_state.can_data_be_received
122+
else:
123+
super().data_received(t)
124+
125+
126+
class EncryptedP2PMisbehaving(BitcoinTestFramework):
127+
def set_test_params(self):
128+
self.num_nodes = 1
129+
self.extra_args = [["-v2transport=1", "-peertimeout=3"]]
130+
131+
def run_test(self):
132+
self.test_earlykeyresponse()
133+
self.test_v2disconnection()
134+
135+
def test_earlykeyresponse(self):
136+
self.log.info('Sending ellswift bytes in parts to ensure that response from responder is received only when')
137+
self.log.info('ellswift bytes have a mismatch from the 16 bytes(network magic followed by "version\\x00\\x00\\x00\\x00\\x00")')
138+
node0 = self.nodes[0]
139+
self.log.info('Sending first 4 bytes of ellswift which match network magic')
140+
self.log.info('If a response is received, assertion failure would happen in our custom data_received() function')
141+
peer1 = node0.add_p2p_connection(MisbehavingV2Peer(TestType.EARLY_KEY_RESPONSE), wait_for_verack=False, send_version=False, supports_v2_p2p=True, wait_for_v2_handshake=False)
142+
peer1.send_raw_message(MAGIC_BYTES['regtest'])
143+
self.log.info('Sending remaining ellswift and garbage which are different from V1_PREFIX. Since a response is')
144+
self.log.info('expected now, our custom data_received() function wouldn\'t result in assertion failure')
145+
peer1.v2_state.can_data_be_received = True
146+
peer1.send_raw_message(peer1.v2_state.ellswift_ours[4:] + peer1.v2_state.sent_garbage)
147+
with node0.assert_debug_log(['V2 handshake timeout peer=0']):
148+
peer1.wait_for_disconnect(timeout=5)
149+
self.log.info('successful disconnection since modified ellswift was sent as response')
150+
151+
def test_v2disconnection(self):
152+
# test v2 disconnection scenarios
153+
node0 = self.nodes[0]
154+
expected_debug_message = [
155+
[], # EARLY_KEY_RESPONSE
156+
["V2 transport error: missing garbage terminator, peer=1"], # EXCESS_GARBAGE
157+
["V2 handshake timeout peer=2"], # WRONG_GARBAGE_TERMINATOR
158+
["V2 transport error: packet decryption failure"], # WRONG_GARBAGE
159+
["V2 transport error: packet decryption failure"], # SEND_NO_AAD
160+
[], # SEND_NON_EMPTY_VERSION_PACKET
161+
]
162+
for test_type in TestType:
163+
if test_type == TestType.EARLY_KEY_RESPONSE:
164+
continue
165+
elif test_type == TestType.SEND_NON_EMPTY_VERSION_PACKET:
166+
node0.add_p2p_connection(MisbehavingV2Peer(test_type), wait_for_verack=True, send_version=True, supports_v2_p2p=True)
167+
self.log.info(f"No disconnection for {test_type.name}")
168+
else:
169+
with node0.assert_debug_log(expected_debug_message[test_type.value], timeout=5):
170+
peer = node0.add_p2p_connection(MisbehavingV2Peer(test_type), wait_for_verack=False, send_version=False, supports_v2_p2p=True, expect_success=False)
171+
peer.wait_for_disconnect()
172+
self.log.info(f"Expected disconnection for {test_type.name}")
173+
174+
175+
if __name__ == '__main__':
176+
EncryptedP2PMisbehaving().main()

test/functional/test_framework/key.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import unittest
1515

1616
from test_framework.crypto import secp256k1
17+
from test_framework.util import random_bitflip
1718

1819
# Point with no known discrete log.
1920
H_POINT = "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"
@@ -292,11 +293,6 @@ def sign_schnorr(key, msg, aux=None, flip_p=False, flip_r=False):
292293
class TestFrameworkKey(unittest.TestCase):
293294
def test_ecdsa_and_schnorr(self):
294295
"""Test the Python ECDSA and Schnorr implementations."""
295-
def random_bitflip(sig):
296-
sig = list(sig)
297-
sig[random.randrange(len(sig))] ^= (1 << (random.randrange(8)))
298-
return bytes(sig)
299-
300296
byte_arrays = [generate_privkey() for _ in range(3)] + [v.to_bytes(32, 'big') for v in [0, ORDER - 1, ORDER, 2**256 - 1]]
301297
keys = {}
302298
for privkey_bytes in byte_arrays: # build array of key/pubkey pairs

test/functional/test_framework/p2p.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ def connection_made(self, transport):
223223
# send the initial handshake immediately
224224
if self.supports_v2_p2p and self.v2_state.initiating and not self.v2_state.tried_v2_handshake:
225225
send_handshake_bytes = self.v2_state.initiate_v2_handshake()
226+
logger.debug(f"sending {len(self.v2_state.sent_garbage)} bytes of garbage data")
226227
self.send_raw_message(send_handshake_bytes)
227228
# for v1 outbound connections, send version message immediately after opening
228229
# (for v2 outbound connections, send it after the initial v2 handshake)
@@ -262,6 +263,7 @@ def _on_data_v2_handshake(self):
262263
self.v2_state = None
263264
return
264265
elif send_handshake_bytes:
266+
logger.debug(f"sending {len(self.v2_state.sent_garbage)} bytes of garbage data")
265267
self.send_raw_message(send_handshake_bytes)
266268
elif send_handshake_bytes == b"":
267269
return # only after send_handshake_bytes are sent can `complete_handshake()` be done

test/functional/test_framework/test_node.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -666,7 +666,7 @@ def assert_start_raises_init_error(self, extra_args=None, expected_msg=None, mat
666666
assert_msg += "with expected error " + expected_msg
667667
self._raise_assertion_error(assert_msg)
668668

669-
def add_p2p_connection(self, p2p_conn, *, wait_for_verack=True, send_version=True, supports_v2_p2p=None, wait_for_v2_handshake=True, **kwargs):
669+
def add_p2p_connection(self, p2p_conn, *, wait_for_verack=True, send_version=True, supports_v2_p2p=None, wait_for_v2_handshake=True, expect_success=True, **kwargs):
670670
"""Add an inbound p2p connection to the node.
671671
672672
This method adds the p2p connection to the self.p2ps list and also
@@ -686,14 +686,15 @@ def add_p2p_connection(self, p2p_conn, *, wait_for_verack=True, send_version=Tru
686686
if supports_v2_p2p is None:
687687
supports_v2_p2p = self.use_v2transport
688688

689-
690689
p2p_conn.p2p_connected_to_node = True
691690
if self.use_v2transport:
692691
kwargs['services'] = kwargs.get('services', P2P_SERVICES) | NODE_P2P_V2
693692
supports_v2_p2p = self.use_v2transport and supports_v2_p2p
694693
p2p_conn.peer_connect(**kwargs, send_version=send_version, net=self.chain, timeout_factor=self.timeout_factor, supports_v2_p2p=supports_v2_p2p)()
695694

696695
self.p2ps.append(p2p_conn)
696+
if not expect_success:
697+
return p2p_conn
697698
p2p_conn.wait_until(lambda: p2p_conn.is_connected, check_connected=False)
698699
if supports_v2_p2p and wait_for_v2_handshake:
699700
p2p_conn.wait_until(lambda: p2p_conn.v2_state.tried_v2_handshake)

test/functional/test_framework/util.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import os
1515
import pathlib
1616
import platform
17+
import random
1718
import re
1819
import time
1920

@@ -247,6 +248,12 @@ def ceildiv(a, b):
247248
return -(-a // b)
248249

249250

251+
def random_bitflip(data):
252+
data = list(data)
253+
data[random.randrange(len(data))] ^= (1 << (random.randrange(8)))
254+
return bytes(data)
255+
256+
250257
def get_fee(tx_size, feerate_btc_kvb):
251258
"""Calculate the fee in BTC given a feerate is BTC/kvB. Reflects CFeeRate::GetFee"""
252259
feerate_sat_kvb = int(feerate_btc_kvb * Decimal(1e8)) # Fee in sat/kvb as an int to avoid float precision errors

0 commit comments

Comments
 (0)