PageRenderTime 45ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/test/functional/p2p_invalid_messages.py

http://github.com/bitcoin/bitcoin
Python | 241 lines | 166 code | 31 blank | 44 comment | 13 complexity | e47181214e7dc67c25d354e890d976e4 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, MIT
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2015-2020 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 asyncio
  7. import struct
  8. import sys
  9. from test_framework import messages
  10. from test_framework.mininode import (
  11. NetworkThread,
  12. P2PDataStore,
  13. P2PInterface,
  14. )
  15. from test_framework.test_framework import BitcoinTestFramework
  16. class msg_unrecognized:
  17. """Nonsensical message. Modeled after similar types in test_framework.messages."""
  18. msgtype = b'badmsg'
  19. def __init__(self, *, str_data):
  20. self.str_data = str_data.encode() if not isinstance(str_data, bytes) else str_data
  21. def serialize(self):
  22. return messages.ser_string(self.str_data)
  23. def __repr__(self):
  24. return "{}(data={})".format(self.msgtype, self.str_data)
  25. class InvalidMessagesTest(BitcoinTestFramework):
  26. def set_test_params(self):
  27. self.num_nodes = 1
  28. self.setup_clean_chain = True
  29. def run_test(self):
  30. """
  31. . Test msg header
  32. 0. Send a bunch of large (4MB) messages of an unrecognized type. Check to see
  33. that it isn't an effective DoS against the node.
  34. 1. Send an oversized (4MB+) message and check that we're disconnected.
  35. 2. Send a few messages with an incorrect data size in the header, ensure the
  36. messages are ignored.
  37. """
  38. self.test_magic_bytes()
  39. self.test_checksum()
  40. self.test_size()
  41. self.test_msgtype()
  42. self.test_large_inv()
  43. node = self.nodes[0]
  44. self.node = node
  45. node.add_p2p_connection(P2PDataStore())
  46. conn2 = node.add_p2p_connection(P2PDataStore())
  47. msg_limit = 4 * 1000 * 1000 # 4MB, per MAX_PROTOCOL_MESSAGE_LENGTH
  48. valid_data_limit = msg_limit - 5 # Account for the 4-byte length prefix
  49. #
  50. # 0.
  51. #
  52. # Send as large a message as is valid, ensure we aren't disconnected but
  53. # also can't exhaust resources.
  54. #
  55. msg_at_size = msg_unrecognized(str_data="b" * valid_data_limit)
  56. assert len(msg_at_size.serialize()) == msg_limit
  57. self.log.info("Sending a bunch of large, junk messages to test memory exhaustion. May take a bit...")
  58. # Run a bunch of times to test for memory exhaustion.
  59. for _ in range(80):
  60. node.p2p.send_message(msg_at_size)
  61. # Check that, even though the node is being hammered by nonsense from one
  62. # connection, it can still service other peers in a timely way.
  63. for _ in range(20):
  64. conn2.sync_with_ping(timeout=2)
  65. # Peer 1, despite serving up a bunch of nonsense, should still be connected.
  66. self.log.info("Waiting for node to drop junk messages.")
  67. node.p2p.sync_with_ping(timeout=400)
  68. assert node.p2p.is_connected
  69. #
  70. # 1.
  71. #
  72. # Send an oversized message, ensure we're disconnected.
  73. #
  74. # Under macOS this test is skipped due to an unexpected error code
  75. # returned from the closing socket which python/asyncio does not
  76. # yet know how to handle.
  77. #
  78. if sys.platform != 'darwin':
  79. msg_over_size = msg_unrecognized(str_data="b" * (valid_data_limit + 1))
  80. assert len(msg_over_size.serialize()) == (msg_limit + 1)
  81. # An unknown message type (or *any* message type) over
  82. # MAX_PROTOCOL_MESSAGE_LENGTH should result in a disconnect.
  83. node.p2p.send_message(msg_over_size)
  84. node.p2p.wait_for_disconnect(timeout=4)
  85. node.disconnect_p2ps()
  86. conn = node.add_p2p_connection(P2PDataStore())
  87. conn.wait_for_verack()
  88. else:
  89. self.log.info("Skipping test p2p_invalid_messages/1 (oversized message) under macOS")
  90. #
  91. # 2.
  92. #
  93. # Send messages with an incorrect data size in the header.
  94. #
  95. actual_size = 100
  96. msg = msg_unrecognized(str_data="b" * actual_size)
  97. # TODO: handle larger-than cases. I haven't been able to pin down what behavior to expect.
  98. for wrong_size in (2, 77, 78, 79):
  99. self.log.info("Sending a message with incorrect size of {}".format(wrong_size))
  100. # Unmodified message should submit okay.
  101. node.p2p.send_and_ping(msg)
  102. # A message lying about its data size results in a disconnect when the incorrect
  103. # data size is less than the actual size.
  104. #
  105. # TODO: why does behavior change at 78 bytes?
  106. #
  107. node.p2p.send_raw_message(self._tweak_msg_data_size(msg, wrong_size))
  108. # For some reason unknown to me, we sometimes have to push additional data to the
  109. # peer in order for it to realize a disconnect.
  110. try:
  111. node.p2p.send_message(messages.msg_ping(nonce=123123))
  112. except IOError:
  113. pass
  114. node.p2p.wait_for_disconnect(timeout=10)
  115. node.disconnect_p2ps()
  116. node.add_p2p_connection(P2PDataStore())
  117. # Node is still up.
  118. conn = node.add_p2p_connection(P2PDataStore())
  119. def test_magic_bytes(self):
  120. conn = self.nodes[0].add_p2p_connection(P2PDataStore())
  121. async def swap_magic_bytes():
  122. conn._on_data = lambda: None # Need to ignore all incoming messages from now, since they come with "invalid" magic bytes
  123. conn.magic_bytes = b'\x00\x11\x22\x32'
  124. # Call .result() to block until the atomic swap is complete, otherwise
  125. # we might run into races later on
  126. asyncio.run_coroutine_threadsafe(swap_magic_bytes(), NetworkThread.network_event_loop).result()
  127. with self.nodes[0].assert_debug_log(['PROCESSMESSAGE: INVALID MESSAGESTART ping']):
  128. conn.send_message(messages.msg_ping(nonce=0xff))
  129. conn.wait_for_disconnect(timeout=1)
  130. self.nodes[0].disconnect_p2ps()
  131. def test_checksum(self):
  132. conn = self.nodes[0].add_p2p_connection(P2PDataStore())
  133. with self.nodes[0].assert_debug_log(['CHECKSUM ERROR (badmsg, 2 bytes), expected 78df0a04 was ffffffff']):
  134. msg = conn.build_message(msg_unrecognized(str_data="d"))
  135. cut_len = (
  136. 4 + # magic
  137. 12 + # msgtype
  138. 4 #len
  139. )
  140. # modify checksum
  141. msg = msg[:cut_len] + b'\xff' * 4 + msg[cut_len + 4:]
  142. self.nodes[0].p2p.send_raw_message(msg)
  143. conn.sync_with_ping(timeout=1)
  144. self.nodes[0].disconnect_p2ps()
  145. def test_size(self):
  146. conn = self.nodes[0].add_p2p_connection(P2PDataStore())
  147. with self.nodes[0].assert_debug_log(['']):
  148. msg = conn.build_message(msg_unrecognized(str_data="d"))
  149. cut_len = (
  150. 4 + # magic
  151. 12 # msgtype
  152. )
  153. # modify len to MAX_SIZE + 1
  154. msg = msg[:cut_len] + struct.pack("<I", 0x02000000 + 1) + msg[cut_len + 4:]
  155. self.nodes[0].p2p.send_raw_message(msg)
  156. conn.wait_for_disconnect(timeout=1)
  157. self.nodes[0].disconnect_p2ps()
  158. def test_msgtype(self):
  159. conn = self.nodes[0].add_p2p_connection(P2PDataStore())
  160. with self.nodes[0].assert_debug_log(['PROCESSMESSAGE: ERRORS IN HEADER']):
  161. msg = msg_unrecognized(str_data="d")
  162. msg.msgtype = b'\xff' * 12
  163. msg = conn.build_message(msg)
  164. # Modify msgtype
  165. msg = msg[:7] + b'\x00' + msg[7 + 1:]
  166. self.nodes[0].p2p.send_raw_message(msg)
  167. conn.sync_with_ping(timeout=1)
  168. self.nodes[0].disconnect_p2ps()
  169. def test_large_inv(self):
  170. conn = self.nodes[0].add_p2p_connection(P2PInterface())
  171. with self.nodes[0].assert_debug_log(['Misbehaving', 'peer=4 (0 -> 20): message inv size() = 50001']):
  172. msg = messages.msg_inv([messages.CInv(1, 1)] * 50001)
  173. conn.send_and_ping(msg)
  174. with self.nodes[0].assert_debug_log(['Misbehaving', 'peer=4 (20 -> 40): message getdata size() = 50001']):
  175. msg = messages.msg_getdata([messages.CInv(1, 1)] * 50001)
  176. conn.send_and_ping(msg)
  177. with self.nodes[0].assert_debug_log(['Misbehaving', 'peer=4 (40 -> 60): headers message size = 2001']):
  178. msg = messages.msg_headers([messages.CBlockHeader()] * 2001)
  179. conn.send_and_ping(msg)
  180. self.nodes[0].disconnect_p2ps()
  181. def _tweak_msg_data_size(self, message, wrong_size):
  182. """
  183. Return a raw message based on another message but with an incorrect data size in
  184. the message header.
  185. """
  186. raw_msg = self.node.p2p.build_message(message)
  187. bad_size_bytes = struct.pack("<I", wrong_size)
  188. num_header_bytes_before_size = 4 + 12
  189. # Replace the correct data size in the message with an incorrect one.
  190. raw_msg_with_wrong_size = (
  191. raw_msg[:num_header_bytes_before_size] +
  192. bad_size_bytes +
  193. raw_msg[(num_header_bytes_before_size + len(bad_size_bytes)):]
  194. )
  195. assert len(raw_msg) == len(raw_msg_with_wrong_size)
  196. return raw_msg_with_wrong_size
  197. if __name__ == '__main__':
  198. InvalidMessagesTest().main()