Skip to content

Commit 024816d

Browse files
committed
Merge #14522: tests: add invalid P2P message tests
d20a9fa tests: add tests for invalid P2P messages (James O'Beirne) 62f94d3 tests: add P2PConnection.send_raw_message (James O'Beirne) 5aa31f6 tests: add utility to assert node memory usage hasn't increased (James O'Beirne) Pull request description: - Adds `p2p_invalid_messages.py`: tests based on behavior for dealing with invalid and malformed P2P messages. Includes a test verifying that we can't DoS a node by spamming it with large invalid messages. - Adds `TestNode.assert_memory_usage_stable`: a context manager that allows us to ensure memory usage doesn't significantly increase on a node during some test. - Adds `P2PConnection.send_raw_message`: which allows us to construct and send messages with tweaked headers. Tree-SHA512: 720a4894c1e6d8f1551b2ae710e5b06c9e4f281524623957cb01599be9afea82671dc26d6152281de0acb87720f0c53b61e2b27d40434d30e525dd9e31fa671f
2 parents 825f779 + d20a9fa commit 024816d

File tree

4 files changed

+230
-6
lines changed

4 files changed

+230
-6
lines changed
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2015-2018 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 node responses to invalid network messages."""
6+
import struct
7+
8+
from test_framework import messages
9+
from test_framework.mininode import P2PDataStore
10+
from test_framework.test_framework import BitcoinTestFramework
11+
12+
13+
class msg_unrecognized:
14+
"""Nonsensical message. Modeled after similar types in test_framework.messages."""
15+
16+
command = b'badmsg'
17+
18+
def __init__(self, str_data):
19+
self.str_data = str_data.encode() if not isinstance(str_data, bytes) else str_data
20+
21+
def serialize(self):
22+
return messages.ser_string(self.str_data)
23+
24+
def __repr__(self):
25+
return "{}(data={})".format(self.command, self.str_data)
26+
27+
28+
class msg_nametoolong(msg_unrecognized):
29+
30+
command = b'thisnameiswayyyyyyyyytoolong'
31+
32+
33+
class InvalidMessagesTest(BitcoinTestFramework):
34+
35+
def set_test_params(self):
36+
self.num_nodes = 1
37+
self.setup_clean_chain = True
38+
39+
def run_test(self):
40+
"""
41+
0. Send a bunch of large (4MB) messages of an unrecognized type. Check to see
42+
that it isn't an effective DoS against the node.
43+
44+
1. Send an oversized (4MB+) message and check that we're disconnected.
45+
46+
2. Send a few messages with an incorrect data size in the header, ensure the
47+
messages are ignored.
48+
49+
3. Send an unrecognized message with a command name longer than 12 characters.
50+
51+
"""
52+
node = self.nodes[0]
53+
self.node = node
54+
node.add_p2p_connection(P2PDataStore())
55+
conn2 = node.add_p2p_connection(P2PDataStore())
56+
57+
msg_limit = 4 * 1000 * 1000 # 4MB, per MAX_PROTOCOL_MESSAGE_LENGTH
58+
valid_data_limit = msg_limit - 5 # Account for the 4-byte length prefix
59+
60+
#
61+
# 0.
62+
#
63+
# Send as large a message as is valid, ensure we aren't disconnected but
64+
# also can't exhaust resources.
65+
#
66+
msg_at_size = msg_unrecognized("b" * valid_data_limit)
67+
assert len(msg_at_size.serialize()) == msg_limit
68+
69+
with node.assert_memory_usage_stable(perc_increase_allowed=0.03):
70+
self.log.info(
71+
"Sending a bunch of large, junk messages to test "
72+
"memory exhaustion. May take a bit...")
73+
74+
# Run a bunch of times to test for memory exhaustion.
75+
for _ in range(200):
76+
node.p2p.send_message(msg_at_size)
77+
78+
# Check that, even though the node is being hammered by nonsense from one
79+
# connection, it can still service other peers in a timely way.
80+
for _ in range(20):
81+
conn2.sync_with_ping(timeout=2)
82+
83+
# Peer 1, despite serving up a bunch of nonsense, should still be connected.
84+
self.log.info("Waiting for node to drop junk messages.")
85+
node.p2p.sync_with_ping(timeout=8)
86+
assert node.p2p.is_connected
87+
88+
#
89+
# 1.
90+
#
91+
# Send an oversized message, ensure we're disconnected.
92+
#
93+
msg_over_size = msg_unrecognized("b" * (valid_data_limit + 1))
94+
assert len(msg_over_size.serialize()) == (msg_limit + 1)
95+
96+
with node.assert_debug_log(["Oversized message from peer=0, disconnecting"]):
97+
# An unknown message type (or *any* message type) over
98+
# MAX_PROTOCOL_MESSAGE_LENGTH should result in a disconnect.
99+
node.p2p.send_message(msg_over_size)
100+
node.p2p.wait_for_disconnect(timeout=4)
101+
102+
node.disconnect_p2ps()
103+
conn = node.add_p2p_connection(P2PDataStore())
104+
conn.wait_for_verack()
105+
106+
#
107+
# 2.
108+
#
109+
# Send messages with an incorrect data size in the header.
110+
#
111+
actual_size = 100
112+
msg = msg_unrecognized("b" * actual_size)
113+
114+
# TODO: handle larger-than cases. I haven't been able to pin down what behavior to expect.
115+
for wrong_size in (2, 77, 78, 79):
116+
self.log.info("Sending a message with incorrect size of {}".format(wrong_size))
117+
118+
# Unmodified message should submit okay.
119+
node.p2p.send_and_ping(msg)
120+
121+
# A message lying about its data size results in a disconnect when the incorrect
122+
# data size is less than the actual size.
123+
#
124+
# TODO: why does behavior change at 78 bytes?
125+
#
126+
node.p2p.send_raw_message(self._tweak_msg_data_size(msg, wrong_size))
127+
128+
# For some reason unknown to me, we sometimes have to push additional data to the
129+
# peer in order for it to realize a disconnect.
130+
try:
131+
node.p2p.send_message(messages.msg_ping(nonce=123123))
132+
except IOError:
133+
pass
134+
135+
node.p2p.wait_for_disconnect(timeout=10)
136+
node.disconnect_p2ps()
137+
node.add_p2p_connection(P2PDataStore())
138+
139+
#
140+
# 3.
141+
#
142+
# Send a message with a too-long command name.
143+
#
144+
node.p2p.send_message(msg_nametoolong("foobar"))
145+
node.p2p.wait_for_disconnect(timeout=4)
146+
147+
# Node is still up.
148+
conn = node.add_p2p_connection(P2PDataStore())
149+
conn.sync_with_ping()
150+
151+
152+
def _tweak_msg_data_size(self, message, wrong_size):
153+
"""
154+
Return a raw message based on another message but with an incorrect data size in
155+
the message header.
156+
"""
157+
raw_msg = self.node.p2p.build_message(message)
158+
159+
bad_size_bytes = struct.pack("<I", wrong_size)
160+
num_header_bytes_before_size = 4 + 12
161+
162+
# Replace the correct data size in the message with an incorrect one.
163+
raw_msg_with_wrong_size = (
164+
raw_msg[:num_header_bytes_before_size] +
165+
bad_size_bytes +
166+
raw_msg[(num_header_bytes_before_size + len(bad_size_bytes)):]
167+
)
168+
assert len(raw_msg) == len(raw_msg_with_wrong_size)
169+
170+
return raw_msg_with_wrong_size
171+
172+
173+
174+
if __name__ == '__main__':
175+
InvalidMessagesTest().main()

test/functional/test_framework/mininode.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -207,10 +207,13 @@ def send_message(self, message):
207207
208208
This method takes a P2P payload, builds the P2P header and adds
209209
the message to the send buffer to be sent over the socket."""
210+
tmsg = self.build_message(message)
211+
self._log_message("send", message)
212+
return self.send_raw_message(tmsg)
213+
214+
def send_raw_message(self, raw_message_bytes):
210215
if not self.is_connected:
211216
raise IOError('Not connected')
212-
self._log_message("send", message)
213-
tmsg = self._build_message(message)
214217

215218
def maybe_write():
216219
if not self._transport:
@@ -220,12 +223,12 @@ def maybe_write():
220223
# Python 3.4 versions.
221224
if hasattr(self._transport, 'is_closing') and self._transport.is_closing():
222225
return
223-
self._transport.write(tmsg)
226+
self._transport.write(raw_message_bytes)
224227
NetworkThread.network_event_loop.call_soon_threadsafe(maybe_write)
225228

226229
# Class utility methods
227230

228-
def _build_message(self, message):
231+
def build_message(self, message):
229232
"""Build a serialized P2P message"""
230233
command = message.command
231234
data = message.serialize()
@@ -409,9 +412,9 @@ def wait_for_verack(self, timeout=60):
409412

410413
# Message sending helper functions
411414

412-
def send_and_ping(self, message):
415+
def send_and_ping(self, message, timeout=60):
413416
self.send_message(message)
414-
self.sync_with_ping()
417+
self.sync_with_ping(timeout=timeout)
415418

416419
# Sync up with the node
417420
def sync_with_ping(self, timeout=60):

test/functional/test_framework/test_node.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,28 @@ def get_deterministic_priv_key(self):
115115
]
116116
return PRIV_KEYS[self.index]
117117

118+
def get_mem_rss(self):
119+
"""Get the memory usage (RSS) per `ps`.
120+
121+
If process is stopped or `ps` is unavailable, return None.
122+
"""
123+
if not (self.running and self.process):
124+
self.log.warning("Couldn't get memory usage; process isn't running.")
125+
return None
126+
127+
try:
128+
return int(subprocess.check_output(
129+
"ps h -o rss {}".format(self.process.pid),
130+
shell=True, stderr=subprocess.DEVNULL).strip())
131+
132+
# Catching `Exception` broadly to avoid failing on platforms where ps
133+
# isn't installed or doesn't work as expected, e.g. OpenBSD.
134+
#
135+
# We could later use something like `psutils` to work across platforms.
136+
except Exception:
137+
self.log.exception("Unable to get memory usage")
138+
return None
139+
118140
def _node_msg(self, msg: str) -> str:
119141
"""Return a modified msg that identifies this node by its index as a debugging aid."""
120142
return "[node %d] %s" % (self.index, msg)
@@ -271,6 +293,29 @@ def assert_debug_log(self, expected_msgs):
271293
if re.search(re.escape(expected_msg), log, flags=re.MULTILINE) is None:
272294
self._raise_assertion_error('Expected message "{}" does not partially match log:\n\n{}\n\n'.format(expected_msg, print_log))
273295

296+
@contextlib.contextmanager
297+
def assert_memory_usage_stable(self, perc_increase_allowed=0.03):
298+
"""Context manager that allows the user to assert that a node's memory usage (RSS)
299+
hasn't increased beyond some threshold percentage.
300+
"""
301+
before_memory_usage = self.get_mem_rss()
302+
303+
yield
304+
305+
after_memory_usage = self.get_mem_rss()
306+
307+
if not (before_memory_usage and after_memory_usage):
308+
self.log.warning("Unable to detect memory usage (RSS) - skipping memory check.")
309+
return
310+
311+
perc_increase_memory_usage = 1 - (float(before_memory_usage) / after_memory_usage)
312+
313+
if perc_increase_memory_usage > perc_increase_allowed:
314+
self._raise_assertion_error(
315+
"Memory usage increased over threshold of {:.3f}% from {} to {} ({:.3f}%)".format(
316+
perc_increase_allowed * 100, before_memory_usage, after_memory_usage,
317+
perc_increase_memory_usage * 100))
318+
274319
def assert_start_raises_init_error(self, extra_args=None, expected_msg=None, match=ErrorMatch.FULL_TEXT, *args, **kwargs):
275320
"""Attempt to start the node and expect it to raise an error.
276321

test/functional/test_runner.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@
136136
'mining_prioritisetransaction.py',
137137
'p2p_invalid_locator.py',
138138
'p2p_invalid_block.py',
139+
'p2p_invalid_messages.py',
139140
'p2p_invalid_tx.py',
140141
'feature_assumevalid.py',
141142
'example_test.py',

0 commit comments

Comments
 (0)