Debian Codegraph @

monero/src/p2p/net_node.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
30
31 #include <boost/algorithm/string/find_iterator.hpp>
32 #include <boost/algorithm/string/finder.hpp>
33 #include <boost/chrono/duration.hpp>
34 #include <boost/endian/conversion.hpp>
35 #include <boost/optional/optional.hpp>
36 #include <boost/thread/future.hpp>
37 #include <boost/utility/string_ref.hpp>
38 #include <chrono>
39 #include <utility>
40
41 #include "common/command_line.h"
42 #include "cryptonote_core/cryptonote_core.h"
43 #include "cryptonote_protocol/cryptonote_protocol_defs.h"
44 #include "net_node.h"
45 #include "net/net_utils_base.h"
46 #include "net/socks.h"
47 #include "net/parse.h"
48 #include "net/tor_address.h"
49 #include "net/i2p_address.h"
50 #include "p2p/p2p_protocol_defs.h"
51 #include "string_tools.h"
52
53 namespace
54 {
55 constexpr const boost::chrono::milliseconds future_poll_interval{500};
56 constexpr const std::chrono::seconds socks_connect_timeout{P2P_DEFAULT_SOCKS_CONNECT_TIMEOUT};
57
58 std::int64_t get_max_connections(const boost::iterator_range<boost::string_ref::const_iterator> value) noexcept
59 {
60 // -1 is default, 0 is error
61 if (value.empty())
62 return -1;
63
64 std::uint32_t out = 0;
65 if (epee::string_tools::get_xtype_from_string(out, std::string{value.begin(), value.end()}))
66 return out;
67 return 0;
68 }
69
70 template<typename T>
71 epee::net_utils::network_address get_address(const boost::string_ref value)
72 {
73 expect<T> address = T::make(value);
74 if (!address)
75 {
76 MERROR(
77 "Failed to parse " << epee::net_utils::zone_to_string(T::get_zone()) << " address \"" << value << "\": " << address.error().message()
78 );
79 return {};
80 }
81 return {std::move(*address)};
82 }
83
84 bool start_socks(std::shared_ptr<net::socks::client> client, const boost::asio::ip::tcp::endpoint& proxy, const epee::net_utils::network_address& remote)
85 {
86 CHECK_AND_ASSERT_MES(client != nullptr, false, "Unexpected null client");
87
88 bool set = false;
89 switch (remote.get_type_id())
90 {
91 case net::tor_address::get_type_id():
92 set = client->set_connect_command(remote.as<net::tor_address>());
93 break;
94 case net::i2p_address::get_type_id():
95 set = client->set_connect_command(remote.as<net::i2p_address>());
96 break;
97 case epee::net_utils::ipv4_network_address::get_type_id():
98 set = client->set_connect_command(remote.as<epee::net_utils::ipv4_network_address>());
99 break;
100 default:
101 MERROR("Unsupported network address in socks_connect");
102 return false;
103 }
104
105 const bool sent =
106 set && net::socks::client::connect_and_send(std::move(client), proxy);
107 CHECK_AND_ASSERT_MES(sent, false, "Unexpected failure to init socks client");
108 return true;
109 }
110 }
111
112 namespace nodetool
113 {
114 const command_line::arg_descriptor<std::string> arg_p2p_bind_ip = {"p2p-bind-ip", "Interface for p2p network protocol (IPv4)", "0.0.0.0"};
115 const command_line::arg_descriptor<std::string> arg_p2p_bind_ipv6_address = {"p2p-bind-ipv6-address", "Interface for p2p network protocol (IPv6)", "::"};
116 const command_line::arg_descriptor<std::string, false, true, 2> arg_p2p_bind_port = {
117 "p2p-bind-port"
118 , "Port for p2p network protocol (IPv4)"
119 , std::to_string(config::P2P_DEFAULT_PORT)
120 , {{ &cryptonote::arg_testnet_on, &cryptonote::arg_stagenet_on }}
121 , [](std::array<bool, 2> testnet_stagenet, bool defaulted, std::string val)->std::string {
122 if (testnet_stagenet[0] && defaulted)
123 return std::to_string(config::testnet::P2P_DEFAULT_PORT);
124 else if (testnet_stagenet[1] && defaulted)
125 return std::to_string(config::stagenet::P2P_DEFAULT_PORT);
126 return val;
127 }
128 };
129 const command_line::arg_descriptor<std::string, false, true, 2> arg_p2p_bind_port_ipv6 = {
130 "p2p-bind-port-ipv6"
131 , "Port for p2p network protocol (IPv6)"
132 , std::to_string(config::P2P_DEFAULT_PORT)
133 , {{ &cryptonote::arg_testnet_on, &cryptonote::arg_stagenet_on }}
134 , [](std::array<bool, 2> testnet_stagenet, bool defaulted, std::string val)->std::string {
135 if (testnet_stagenet[0] && defaulted)
136 return std::to_string(config::testnet::P2P_DEFAULT_PORT);
137 else if (testnet_stagenet[1] && defaulted)
138 return std::to_string(config::stagenet::P2P_DEFAULT_PORT);
139 return val;
140 }
141 };
142
143 const command_line::arg_descriptor<uint32_t> arg_p2p_external_port = {"p2p-external-port", "External port for p2p network protocol (if port forwarding used with NAT)", 0};
144 const command_line::arg_descriptor<bool> arg_p2p_allow_local_ip = {"allow-local-ip", "Allow local ip add to peer list, mostly in debug purposes"};
145 const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_peer = {"add-peer", "Manually add peer to local peerlist"};
146 const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_priority_node = {"add-priority-node", "Specify list of peers to connect to and attempt to keep the connection open"};
147 const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_exclusive_node = {"add-exclusive-node", "Specify list of peers to connect to only."
148 " If this option is given the options add-priority-node and seed-node are ignored"};
149 const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_seed_node = {"seed-node", "Connect to a node to retrieve peer addresses, and disconnect"};
150 const command_line::arg_descriptor<std::vector<std::string> > arg_tx_proxy = {"tx-proxy", "Send local txes through proxy: <network-type>,<socks-ip:port>[,max_connections][,disable_noise] i.e. \"tor,127.0.0.1:9050,100,disable_noise\""};
151 const command_line::arg_descriptor<std::vector<std::string> > arg_anonymous_inbound = {"anonymous-inbound", "<hidden-service-address>,<[bind-ip:]port>[,max_connections] i.e. \"x.onion,127.0.0.1:18083,100\""};
152 const command_line::arg_descriptor<std::string> arg_ban_list = {"ban-list", "Specify ban list file, one IP address per line"};
153 const command_line::arg_descriptor<bool> arg_p2p_hide_my_port = {"hide-my-port", "Do not announce yourself as peerlist candidate", false, true};
154 const command_line::arg_descriptor<bool> arg_no_sync = {"no-sync", "Don't synchronize the blockchain with other peers", false};
155 const command_line::arg_descriptor<bool> arg_enable_dns_blocklist = {"enable-dns-blocklist", "Apply realtime blocklist from DNS", false};
156
157 const command_line::arg_descriptor<bool> arg_no_igd = {"no-igd", "Disable UPnP port mapping"};
158 const command_line::arg_descriptor<std::string> arg_igd = {"igd", "UPnP port mapping (disabled, enabled, delayed)", "delayed"};
159 const command_line::arg_descriptor<bool> arg_p2p_use_ipv6 = {"p2p-use-ipv6", "Enable IPv6 for p2p", false};
160 const command_line::arg_descriptor<bool> arg_p2p_ignore_ipv4 = {"p2p-ignore-ipv4", "Ignore unsuccessful IPv4 bind for p2p", false};
161 const command_line::arg_descriptor<int64_t> arg_out_peers = {"out-peers", "set max number of out peers", -1};
162 const command_line::arg_descriptor<int64_t> arg_in_peers = {"in-peers", "set max number of in peers", -1};
163 const command_line::arg_descriptor<int> arg_tos_flag = {"tos-flag", "set TOS flag", -1};
164
165 const command_line::arg_descriptor<int64_t> arg_limit_rate_up = {"limit-rate-up", "set limit-rate-up [kB/s]", P2P_DEFAULT_LIMIT_RATE_UP};
166 const command_line::arg_descriptor<int64_t> arg_limit_rate_down = {"limit-rate-down", "set limit-rate-down [kB/s]", P2P_DEFAULT_LIMIT_RATE_DOWN};
167 const command_line::arg_descriptor<int64_t> arg_limit_rate = {"limit-rate", "set limit-rate [kB/s]", -1};
168
169 const command_line::arg_descriptor<bool> arg_pad_transactions = {
170 "pad-transactions", "Pad relayed transactions to help defend against traffic volume analysis", false
171 };
172 const command_line::arg_descriptor<uint32_t> arg_max_connections_per_ip = {"max-connections-per-ip", "Maximum number of p2p connections allowed from the same IP address", 1};
173
174 boost::optional<std::vector<proxy>> get_proxies(boost::program_options::variables_map const& vm)
175 {
176 namespace ip = boost::asio::ip;
177
178 std::vector<proxy> proxies{};
179
180 const std::vector<std::string> args = command_line::get_arg(vm, arg_tx_proxy);
181 proxies.reserve(args.size());
182
183 for (const boost::string_ref arg : args)
184 {
185 proxies.emplace_back();
186
187 auto next = boost::algorithm::make_split_iterator(arg, boost::algorithm::first_finder(","));
188 CHECK_AND_ASSERT_MES(!next.eof() && !next->empty(), boost::none, "No network type for --" << arg_tx_proxy.name);
189 const boost::string_ref zone{next->begin(), next->size()};
190
191 ++next;
192 CHECK_AND_ASSERT_MES(!next.eof() && !next->empty(), boost::none, "No ipv4:port given for --" << arg_tx_proxy.name);
193 const boost::string_ref proxy{next->begin(), next->size()};
194
195 ++next;
196 for (unsigned count = 0; !next.eof(); ++count, ++next)
197 {
198 if (2 <= count)
199 {
200 MERROR("Too many ',' characters given to --" << arg_tx_proxy.name);
201 return boost::none;
202 }
203
204 if (boost::string_ref{next->begin(), next->size()} == "disable_noise")
205 proxies.back().noise = false;
206 else
207 {
208 proxies.back().max_connections = get_max_connections(*next);
209 if (proxies.back().max_connections == 0)
210 {
211 MERROR("Invalid max connections given to --" << arg_tx_proxy.name);
212 return boost::none;
213 }
214 }
215 }
216
217 switch (epee::net_utils::zone_from_string(zone))
218 {
219 case epee::net_utils::zone::tor:
220 proxies.back().zone = epee::net_utils::zone::tor;
221 break;
222 case epee::net_utils::zone::i2p:
223 proxies.back().zone = epee::net_utils::zone::i2p;
224 break;
225 default:
226 MERROR("Invalid network for --" << arg_tx_proxy.name);
227 return boost::none;
228 }
229
230 std::uint32_t ip = 0;
231 std::uint16_t port = 0;
232 if (!epee::string_tools::parse_peer_from_string(ip, port, std::string{proxy}) || port == 0)
233 {
234 MERROR("Invalid ipv4:port given for --" << arg_tx_proxy.name);
235 return boost::none;
236 }
237 proxies.back().address = ip::tcp::endpoint{ip::address_v4{boost::endian::native_to_big(ip)}, port};
238 }
239
240 return proxies;
241 }
242
243 boost::optional<std::vector<anonymous_inbound>> get_anonymous_inbounds(boost::program_options::variables_map const& vm)
244 {
245 std::vector<anonymous_inbound> inbounds{};
246
247 const std::vector<std::string> args = command_line::get_arg(vm, arg_anonymous_inbound);
248 inbounds.reserve(args.size());
249
250 for (const boost::string_ref arg : args)
251 {
252 inbounds.emplace_back();
253
254 auto next = boost::algorithm::make_split_iterator(arg, boost::algorithm::first_finder(","));
255 CHECK_AND_ASSERT_MES(!next.eof() && !next->empty(), boost::none, "No inbound address for --" << arg_anonymous_inbound.name);
256 const boost::string_ref address{next->begin(), next->size()};
257
258 ++next;
259 CHECK_AND_ASSERT_MES(!next.eof() && !next->empty(), boost::none, "No local ipv4:port given for --" << arg_anonymous_inbound.name);
260 const boost::string_ref bind{next->begin(), next->size()};
261
262 const std::size_t colon = bind.find_first_of(':');
263 CHECK_AND_ASSERT_MES(colon < bind.size(), boost::none, "No local port given for --" << arg_anonymous_inbound.name);
264
265 ++next;
266 if (!next.eof())
267 {
268 inbounds.back().max_connections = get_max_connections(*next);
269 if (inbounds.back().max_connections == 0)
270 {
271 MERROR("Invalid max connections given to --" << arg_tx_proxy.name);
272 return boost::none;
273 }
274 }
275
276 expect<epee::net_utils::network_address> our_address = net::get_network_address(address, 0);
277 switch (our_address ? our_address->get_type_id() : epee::net_utils::address_type::invalid)
278 {
279 case net::tor_address::get_type_id():
280 inbounds.back().our_address = std::move(*our_address);
281 inbounds.back().default_remote = net::tor_address::unknown();
282 break;
283 case net::i2p_address::get_type_id():
284 inbounds.back().our_address = std::move(*our_address);
285 inbounds.back().default_remote = net::i2p_address::unknown();
286 break;
287 default:
288 MERROR("Invalid inbound address (" << address << ") for --" << arg_anonymous_inbound.name << ": " << (our_address ? "invalid type" : our_address.error().message()));
289 return boost::none;
290 }
291
292 // get_address returns default constructed address on error
293 if (inbounds.back().our_address == epee::net_utils::network_address{})
294 return boost::none;
295
296 std::uint32_t ip = 0;
297 std::uint16_t port = 0;
298 if (!epee::string_tools::parse_peer_from_string(ip, port, std::string{bind}))
299 {
300 MERROR("Invalid ipv4:port given for --" << arg_anonymous_inbound.name);
301 return boost::none;
302 }
303 inbounds.back().local_ip = std::string{bind.substr(0, colon)};
304 inbounds.back().local_port = std::string{bind.substr(colon + 1)};
305 }
306
307 return inbounds;
308 }
309
310 bool is_filtered_command(const epee::net_utils::network_address& address, int command)
311 {
312 switch (command)
313 {
314 case nodetool::COMMAND_HANDSHAKE_T<cryptonote::CORE_SYNC_DATA>::ID:
315 case nodetool::COMMAND_TIMED_SYNC_T<cryptonote::CORE_SYNC_DATA>::ID:
316 case cryptonote::NOTIFY_NEW_TRANSACTIONS::ID:
317 return false;
318 default:
319 break;
320 }
321
322 if (address.get_zone() == epee::net_utils::zone::public_)
323 return false;
324
325 MWARNING("Filtered command (#" << command << ") to/from " << address.str());
326 return true;
327 }
328
329 boost::optional<boost::asio::ip::tcp::socket>
330 socks_connect_internal(const std::atomic<bool>& stop_signal, boost::asio::io_context& service, const boost::asio::ip::tcp::endpoint& proxy, const epee::net_utils::network_address& remote)
331 {
332 using socket_type = net::socks::client::stream_type::socket;
333 using client_result = std::pair<boost::system::error_code, socket_type>;
334
335 struct notify
336 {
337 boost::promise<client_result> socks_promise;
338
339 void operator()(boost::system::error_code error, socket_type&& sock)
340 {
341 socks_promise.set_value(std::make_pair(error, std::move(sock)));
342 }
343 };
344
345 net::socks::client::close_on_exit close_client{};
346 boost::unique_future<client_result> socks_result{};
347 {
348 boost::promise<client_result> socks_promise{};
349 socks_result = socks_promise.get_future();
350
351 auto client = net::socks::make_connect_client(
352 boost::asio::ip::tcp::socket{service}, net::socks::version::v4a, notify{std::move(socks_promise)}
353 );
354 close_client.self = client;
355 if (!start_socks(std::move(client), proxy, remote))
356 return boost::none;
357 }
358
359 const auto start = std::chrono::steady_clock::now();
360 while (socks_result.wait_for(future_poll_interval) == boost::future_status::timeout)
361 {
362 if (socks_connect_timeout < std::chrono::steady_clock::now() - start)
363 {
364 MERROR("Timeout on socks connect (" << proxy << " to " << remote.str() << ")");
365 return boost::none;
366 }
367
368 if (stop_signal)
369 return boost::none;
370 }
371
372 try
373 {
374 auto result = socks_result.get();
375 if (!result.first)
376 {
377 close_client.self.reset();
378 return {std::move(result.second)};
379 }
380
381 MERROR("Failed to make socks connection to " << remote.str() << " (via " << proxy << "): " << result.first.message());
382 }
383 catch (boost::broken_promise const&)
384 {}
385
386 return boost::none;
387 }
388 }