Branch data Line data Source code
1 : : // Copyright (c) 2024-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or https://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #include <common/pcp.h>
6 : :
7 : : #include <compat/compat.h>
8 : : #include <crypto/common.h>
9 : : #include <crypto/hex_base.h>
10 : : #include <netaddress.h>
11 : : #include <netbase.h>
12 : : #include <tinyformat.h>
13 : : #include <util/check.h>
14 : : #include <util/log.h>
15 : : #include <util/sock.h>
16 : : #include <util/string.h>
17 : : #include <util/threadinterrupt.h>
18 : : #include <util/time.h>
19 : :
20 : : #include <algorithm>
21 : : #include <compare>
22 : : #include <cstring>
23 : : #include <functional>
24 : : #include <map>
25 : : #include <memory>
26 : : #include <optional>
27 : : #include <span>
28 : : #include <utility>
29 : : #include <vector>
30 : :
31 : : namespace {
32 : :
33 : : // RFC6886 NAT-PMP and RFC6887 Port Control Protocol (PCP) implementation.
34 : : // NAT-PMP and PCP use network byte order (big-endian).
35 : :
36 : : // NAT-PMP (v0) protocol constants.
37 : : //! NAT-PMP uses a fixed server port number (RFC6887 section 1.1).
38 : : constexpr uint16_t NATPMP_SERVER_PORT = 5351;
39 : : //! Version byte for NATPMP (RFC6886 1.1)
40 : : constexpr uint8_t NATPMP_VERSION = 0;
41 : : //! Request opcode base (RFC6886 3).
42 : : constexpr uint8_t NATPMP_REQUEST = 0x00;
43 : : //! Response opcode base (RFC6886 3).
44 : : constexpr uint8_t NATPMP_RESPONSE = 0x80;
45 : : //! Get external address (RFC6886 3.2)
46 : : constexpr uint8_t NATPMP_OP_GETEXTERNAL = 0x00;
47 : : //! Map TCP port (RFC6886 3.3)
48 : : constexpr uint8_t NATPMP_OP_MAP_TCP = 0x02;
49 : : //! Shared request header size in bytes.
50 : : constexpr size_t NATPMP_REQUEST_HDR_SIZE = 2;
51 : : //! Shared response header (minimum) size in bytes.
52 : : constexpr size_t NATPMP_RESPONSE_HDR_SIZE = 8;
53 : : //! GETEXTERNAL request size in bytes, including header (RFC6886 3.2).
54 : : constexpr size_t NATPMP_GETEXTERNAL_REQUEST_SIZE = NATPMP_REQUEST_HDR_SIZE + 0;
55 : : //! GETEXTERNAL response size in bytes, including header (RFC6886 3.2).
56 : : constexpr size_t NATPMP_GETEXTERNAL_RESPONSE_SIZE = NATPMP_RESPONSE_HDR_SIZE + 4;
57 : : //! MAP request size in bytes, including header (RFC6886 3.3).
58 : : constexpr size_t NATPMP_MAP_REQUEST_SIZE = NATPMP_REQUEST_HDR_SIZE + 10;
59 : : //! MAP response size in bytes, including header (RFC6886 3.3).
60 : : constexpr size_t NATPMP_MAP_RESPONSE_SIZE = NATPMP_RESPONSE_HDR_SIZE + 8;
61 : :
62 : : // Shared header offsets (RFC6886 3.2, 3.3), relative to start of packet.
63 : : //! Offset of version field in packets.
64 : : constexpr size_t NATPMP_HDR_VERSION_OFS = 0;
65 : : //! Offset of opcode field in packets
66 : : constexpr size_t NATPMP_HDR_OP_OFS = 1;
67 : : //! Offset of result code in packets. Result codes are 16 bit in NAT-PMP instead of 8 bit in PCP.
68 : : constexpr size_t NATPMP_RESPONSE_HDR_RESULT_OFS = 2;
69 : :
70 : : // GETEXTERNAL response offsets (RFC6886 3.2), relative to start of packet.
71 : : //! Returned external address
72 : : constexpr size_t NATPMP_GETEXTERNAL_RESPONSE_IP_OFS = 8;
73 : :
74 : : // MAP request offsets (RFC6886 3.3), relative to start of packet.
75 : : //! Internal port to be mapped.
76 : : constexpr size_t NATPMP_MAP_REQUEST_INTERNAL_PORT_OFS = 4;
77 : : //! Suggested external port for mapping.
78 : : constexpr size_t NATPMP_MAP_REQUEST_EXTERNAL_PORT_OFS = 6;
79 : : //! Requested port mapping lifetime in seconds.
80 : : constexpr size_t NATPMP_MAP_REQUEST_LIFETIME_OFS = 8;
81 : :
82 : : // MAP response offsets (RFC6886 3.3), relative to start of packet.
83 : : //! Internal port for mapping (will match internal port of request).
84 : : constexpr size_t NATPMP_MAP_RESPONSE_INTERNAL_PORT_OFS = 8;
85 : : //! External port for mapping.
86 : : constexpr size_t NATPMP_MAP_RESPONSE_EXTERNAL_PORT_OFS = 10;
87 : : //! Created port mapping lifetime in seconds.
88 : : constexpr size_t NATPMP_MAP_RESPONSE_LIFETIME_OFS = 12;
89 : :
90 : : // Relevant NETPMP result codes (RFC6886 3.5).
91 : : //! Result code representing success status.
92 : : constexpr uint8_t NATPMP_RESULT_SUCCESS = 0;
93 : : //! Result code representing unsupported version.
94 : : constexpr uint8_t NATPMP_RESULT_UNSUPP_VERSION = 1;
95 : : //! Result code representing not authorized (router doesn't support port mapping).
96 : : constexpr uint8_t NATPMP_RESULT_NOT_AUTHORIZED = 2;
97 : : //! Result code representing lack of resources.
98 : : constexpr uint8_t NATPMP_RESULT_NO_RESOURCES = 4;
99 : :
100 : : //! Mapping of NATPMP result code to string (RFC6886 3.5). Result codes <=2 match PCP.
101 : : const std::map<uint16_t, std::string> NATPMP_RESULT_STR{
102 : : {0, "SUCCESS"},
103 : : {1, "UNSUPP_VERSION"},
104 : : {2, "NOT_AUTHORIZED"},
105 : : {3, "NETWORK_FAILURE"},
106 : : {4, "NO_RESOURCES"},
107 : : {5, "UNSUPP_OPCODE"},
108 : : };
109 : :
110 : : // PCP (v2) protocol constants.
111 : : //! Maximum packet size in bytes (RFC6887 section 7).
112 : : constexpr size_t PCP_MAX_SIZE = 1100;
113 : : //! PCP uses a fixed server port number (RFC6887 section 19.1). Shared with NAT-PMP.
114 : : constexpr uint16_t PCP_SERVER_PORT = NATPMP_SERVER_PORT;
115 : : //! Version byte. 0 is NAT-PMP (RFC6886), 1 is forbidden, 2 for PCP (RFC6887).
116 : : constexpr uint8_t PCP_VERSION = 2;
117 : : //! PCP Request Header. See RFC6887 section 7.1. Shared with NAT-PMP.
118 : : constexpr uint8_t PCP_REQUEST = NATPMP_REQUEST; // R = 0
119 : : //! PCP Response Header. See RFC6887 section 7.2. Shared with NAT-PMP.
120 : : constexpr uint8_t PCP_RESPONSE = NATPMP_RESPONSE; // R = 1
121 : : //! Map opcode. See RFC6887 section 19.2
122 : : constexpr uint8_t PCP_OP_MAP = 0x01;
123 : : //! TCP protocol number (IANA).
124 : : constexpr uint16_t PCP_PROTOCOL_TCP = 6;
125 : : //! Request and response header size in bytes (RFC6887 section 7.1).
126 : : constexpr size_t PCP_HDR_SIZE = 24;
127 : : //! Map request and response size in bytes (RFC6887 section 11.1).
128 : : constexpr size_t PCP_MAP_SIZE = 36;
129 : :
130 : : // Header offsets shared between request and responses (RFC6887 7.1, 7.2), relative to start of packet.
131 : : //! Version field (1 byte).
132 : : constexpr size_t PCP_HDR_VERSION_OFS = NATPMP_HDR_VERSION_OFS;
133 : : //! Opcode field (1 byte).
134 : : constexpr size_t PCP_HDR_OP_OFS = NATPMP_HDR_OP_OFS;
135 : : //! Requested lifetime (request), granted lifetime (response) (4 bytes).
136 : : constexpr size_t PCP_HDR_LIFETIME_OFS = 4;
137 : :
138 : : // Request header offsets (RFC6887 7.1), relative to start of packet.
139 : : //! PCP client's IP address (16 bytes).
140 : : constexpr size_t PCP_REQUEST_HDR_IP_OFS = 8;
141 : :
142 : : // Response header offsets (RFC6887 7.2), relative to start of packet.
143 : : //! Result code (1 byte).
144 : : constexpr size_t PCP_RESPONSE_HDR_RESULT_OFS = 3;
145 : :
146 : : // MAP request/response offsets (RFC6887 11.1), relative to start of opcode-specific data.
147 : : //! Mapping nonce (12 bytes).
148 : : constexpr size_t PCP_MAP_NONCE_OFS = 0;
149 : : //! Protocol (1 byte).
150 : : constexpr size_t PCP_MAP_PROTOCOL_OFS = 12;
151 : : //! Internal port for mapping (2 bytes).
152 : : constexpr size_t PCP_MAP_INTERNAL_PORT_OFS = 16;
153 : : //! Suggested external port (request), assigned external port (response) (2 bytes).
154 : : constexpr size_t PCP_MAP_EXTERNAL_PORT_OFS = 18;
155 : : //! Suggested external IP (request), assigned external IP (response) (16 bytes).
156 : : constexpr size_t PCP_MAP_EXTERNAL_IP_OFS = 20;
157 : :
158 : : //! Result code representing success (RFC6887 7.4), shared with NAT-PMP.
159 : : constexpr uint8_t PCP_RESULT_SUCCESS = NATPMP_RESULT_SUCCESS;
160 : : //! Result code representing not authorized (RFC6887 7.4), shared with NAT-PMP.
161 : : constexpr uint8_t PCP_RESULT_NOT_AUTHORIZED = NATPMP_RESULT_NOT_AUTHORIZED;
162 : : //! Result code representing lack of resources (RFC6887 7.4).
163 : : constexpr uint8_t PCP_RESULT_NO_RESOURCES = 8;
164 : :
165 : : //! Mapping of PCP result code to string (RFC6887 7.4). Result codes <=2 match NAT-PMP.
166 : : const std::map<uint8_t, std::string> PCP_RESULT_STR{
167 : : {0, "SUCCESS"},
168 : : {1, "UNSUPP_VERSION"},
169 : : {2, "NOT_AUTHORIZED"},
170 : : {3, "MALFORMED_REQUEST"},
171 : : {4, "UNSUPP_OPCODE"},
172 : : {5, "UNSUPP_OPTION"},
173 : : {6, "MALFORMED_OPTION"},
174 : : {7, "NETWORK_FAILURE"},
175 : : {8, "NO_RESOURCES"},
176 : : {9, "UNSUPP_PROTOCOL"},
177 : : {10, "USER_EX_QUOTA"},
178 : : {11, "CANNOT_PROVIDE_EXTERNAL"},
179 : : {12, "ADDRESS_MISMATCH"},
180 : : {13, "EXCESSIVE_REMOTE_PEER"},
181 : : };
182 : :
183 : : //! Return human-readable string from NATPMP result code.
184 : 2 : std::string NATPMPResultString(uint16_t result_code)
185 : : {
186 : 2 : auto result_i = NATPMP_RESULT_STR.find(result_code);
187 [ + - - - : 4 : return strprintf("%s (code %d)", result_i == NATPMP_RESULT_STR.end() ? "(unknown)" : result_i->second, result_code);
+ - ]
188 : : }
189 : :
190 : : //! Return human-readable string from PCP result code.
191 : 2 : std::string PCPResultString(uint8_t result_code)
192 : : {
193 : 2 : auto result_i = PCP_RESULT_STR.find(result_code);
194 [ + + - + : 5 : return strprintf("%s (code %d)", result_i == PCP_RESULT_STR.end() ? "(unknown)" : result_i->second, result_code);
+ - ]
195 : : }
196 : :
197 : : //! Wrap address in IPv6 according to RFC6887. wrapped_addr needs to be able to store 16 bytes.
198 : 16 : [[nodiscard]] bool PCPWrapAddress(std::span<uint8_t> wrapped_addr, const CNetAddr &addr)
199 : : {
200 [ + + ]: 16 : Assume(wrapped_addr.size() == ADDR_IPV6_SIZE);
201 [ + + ]: 16 : if (addr.IsIPv4()) {
202 : 12 : struct in_addr addr4;
203 [ + - ]: 12 : if (!addr.GetInAddr(&addr4)) return false;
204 : : // Section 5: "When the address field holds an IPv4 address, an IPv4-mapped IPv6 address [RFC4291] is used (::ffff:0:0/96)."
205 : 12 : std::memcpy(wrapped_addr.data(), IPV4_IN_IPV6_PREFIX.data(), IPV4_IN_IPV6_PREFIX.size());
206 : 12 : std::memcpy(wrapped_addr.data() + IPV4_IN_IPV6_PREFIX.size(), &addr4, ADDR_IPV4_SIZE);
207 : 12 : return true;
208 [ + - ]: 4 : } else if (addr.IsIPv6()) {
209 : 4 : struct in6_addr addr6;
210 [ + - ]: 4 : if (!addr.GetIn6Addr(&addr6)) return false;
211 : 4 : std::memcpy(wrapped_addr.data(), &addr6, ADDR_IPV6_SIZE);
212 : 4 : return true;
213 : : } else {
214 : : return false;
215 : : }
216 : : }
217 : :
218 : : //! Unwrap PCP-encoded address according to RFC6887.
219 : 5 : CNetAddr PCPUnwrapAddress(std::span<const uint8_t> wrapped_addr)
220 : : {
221 [ + + ]: 5 : Assume(wrapped_addr.size() == ADDR_IPV6_SIZE);
222 [ + + ]: 5 : if (util::HasPrefix(wrapped_addr, IPV4_IN_IPV6_PREFIX)) {
223 : 2 : struct in_addr addr4;
224 : 2 : std::memcpy(&addr4, wrapped_addr.data() + IPV4_IN_IPV6_PREFIX.size(), ADDR_IPV4_SIZE);
225 : 2 : return CNetAddr(addr4);
226 : : } else {
227 : 3 : struct in6_addr addr6;
228 : 3 : std::memcpy(&addr6, wrapped_addr.data(), ADDR_IPV6_SIZE);
229 : 3 : return CNetAddr(addr6);
230 : : }
231 : : }
232 : :
233 : : //! PCP or NAT-PMP send-receive loop.
234 : 13 : std::optional<std::vector<uint8_t>> PCPSendRecv(Sock &sock, const std::string &protocol, std::span<const uint8_t> request, int num_tries,
235 : : std::chrono::milliseconds timeout_per_try,
236 : : std::function<bool(std::span<const uint8_t>)> check_packet,
237 : : CThreadInterrupt& interrupt)
238 : : {
239 : 13 : using namespace std::chrono;
240 : : // UDP is a potentially lossy protocol, so we try to send again a few times.
241 : 13 : uint8_t response[PCP_MAX_SIZE];
242 : 13 : bool got_response = false;
243 : 13 : int recvsz = 0;
244 [ + + + + ]: 28 : for (int ntry = 0; !got_response && ntry < num_tries; ++ntry) {
245 [ + + ]: 16 : if (ntry > 0) {
246 [ + - ]: 3 : LogDebug(BCLog::NET, "%s: Retrying (%d)\n", protocol, ntry);
247 : : }
248 : : // Dispatch packet to gateway.
249 [ - + ]: 16 : if (sock.Send(request.data(), request.size(), 0) != static_cast<ssize_t>(request.size())) {
250 [ # # # # ]: 0 : LogDebug(BCLog::NET, "%s: Could not send request: %s\n", protocol, NetworkErrorString(WSAGetLastError()));
251 : 0 : return std::nullopt; // Network-level error, probably no use retrying.
252 : : }
253 : :
254 : : // Wait for response(s) until we get a valid response, a network error, or time out.
255 : 16 : auto cur_time = time_point_cast<milliseconds>(MockableSteadyClock::now());
256 : 16 : auto deadline = cur_time + timeout_per_try;
257 [ + - ]: 16 : while ((cur_time = time_point_cast<milliseconds>(MockableSteadyClock::now())) < deadline) {
258 [ - + ]: 16 : if (interrupt) return std::nullopt;
259 : 16 : Sock::Event occurred = 0;
260 [ - + ]: 16 : if (!sock.Wait(deadline - cur_time, Sock::RecvEvent, &occurred)) {
261 [ # # ]: 0 : LogWarning("%s: Could not wait on socket: %s\n", protocol, NetworkErrorString(WSAGetLastError()));
262 : 0 : return std::nullopt; // Network-level error, probably no use retrying.
263 : : }
264 [ + + ]: 16 : if (!occurred) {
265 [ + - ]: 4 : LogDebug(BCLog::NET, "%s: Timeout\n", protocol);
266 : : break; // Retry.
267 : : }
268 : :
269 : : // Receive response.
270 : 12 : recvsz = sock.Recv(response, sizeof(response), MSG_DONTWAIT);
271 [ + + ]: 12 : if (recvsz < 0) {
272 [ + - + - ]: 1 : LogDebug(BCLog::NET, "%s: Could not receive response: %s\n", protocol, NetworkErrorString(WSAGetLastError()));
273 : 1 : return std::nullopt; // Network-level error, probably no use retrying.
274 : : }
275 [ + - + - ]: 11 : LogDebug(BCLog::NET, "%s: Received response of %d bytes: %s\n", protocol, recvsz, HexStr(std::span(response, recvsz)));
276 : :
277 [ - + ]: 11 : if (check_packet(std::span<uint8_t>(response, recvsz))) {
278 : : got_response = true; // Got expected response, break from receive loop as well as from retry loop.
279 : : break;
280 : : }
281 : : }
282 : : }
283 [ + + ]: 12 : if (!got_response) {
284 [ + - ]: 1 : LogDebug(BCLog::NET, "%s: Giving up after %d tries\n", protocol, num_tries);
285 : 1 : return std::nullopt;
286 : : }
287 : 11 : return std::vector<uint8_t>(response, response + recvsz);
288 : : }
289 : :
290 : : }
291 : :
292 : 3 : std::variant<MappingResult, MappingError> NATPMPRequestPortMap(const CNetAddr &gateway, uint16_t port, uint32_t lifetime, CThreadInterrupt& interrupt, int num_tries, std::chrono::milliseconds timeout_per_try)
293 : : {
294 : 3 : struct sockaddr_storage dest_addr;
295 : 3 : socklen_t dest_addrlen = sizeof(struct sockaddr_storage);
296 : :
297 [ + - + - ]: 3 : LogDebug(BCLog::NET, "natpmp: Requesting port mapping port %d from gateway %s\n", port, gateway.ToStringAddr());
298 : :
299 : : // Validate gateway, make sure it's IPv4. NAT-PMP does not support IPv6.
300 [ + - - + ]: 3 : if (!CService(gateway, PCP_SERVER_PORT).GetSockAddr((struct sockaddr*)&dest_addr, &dest_addrlen)) return MappingError::NETWORK_ERROR;
301 [ - + ]: 3 : if (dest_addr.ss_family != AF_INET) return MappingError::NETWORK_ERROR;
302 : :
303 : : // Create IPv4 UDP socket
304 : 3 : auto sock{CreateSock(AF_INET, SOCK_DGRAM, IPPROTO_UDP)};
305 [ - + ]: 3 : if (!sock) {
306 [ # # # # ]: 0 : LogWarning("natpmp: Could not create UDP socket: %s\n", NetworkErrorString(WSAGetLastError()));
307 : 0 : return MappingError::NETWORK_ERROR;
308 : : }
309 : :
310 : : // Associate UDP socket to gateway.
311 [ + - - + ]: 3 : if (sock->Connect((struct sockaddr*)&dest_addr, dest_addrlen) != 0) {
312 [ # # # # ]: 0 : LogWarning("natpmp: Could not connect to gateway: %s\n", NetworkErrorString(WSAGetLastError()));
313 : 0 : return MappingError::NETWORK_ERROR;
314 : : }
315 : :
316 : : // Use getsockname to get the address toward the default gateway (the internal address).
317 : 3 : struct sockaddr_in internal;
318 : 3 : socklen_t internal_addrlen = sizeof(struct sockaddr_in);
319 [ + - - + ]: 3 : if (sock->GetSockName((struct sockaddr*)&internal, &internal_addrlen) != 0) {
320 [ # # # # ]: 0 : LogWarning("natpmp: Could not get sock name: %s\n", NetworkErrorString(WSAGetLastError()));
321 : 0 : return MappingError::NETWORK_ERROR;
322 : : }
323 : :
324 : : // Request external IP address (RFC6886 section 3.2).
325 [ + - ]: 3 : std::vector<uint8_t> request(NATPMP_GETEXTERNAL_REQUEST_SIZE);
326 [ - + ]: 3 : request[NATPMP_HDR_VERSION_OFS] = NATPMP_VERSION;
327 : 3 : request[NATPMP_HDR_OP_OFS] = NATPMP_REQUEST | NATPMP_OP_GETEXTERNAL;
328 : :
329 [ - + + - ]: 6 : auto recv_res = PCPSendRecv(*sock, "natpmp", request, num_tries, timeout_per_try,
330 [ - + ]: 3 : [&](const std::span<const uint8_t> response) -> bool {
331 [ - + ]: 3 : if (response.size() < NATPMP_GETEXTERNAL_RESPONSE_SIZE) {
332 : 0 : LogWarning("natpmp: Response too small\n");
333 : 0 : return false; // Wasn't response to what we expected, try receiving next packet.
334 : : }
335 [ + - - + ]: 3 : if (response[NATPMP_HDR_VERSION_OFS] != NATPMP_VERSION || response[NATPMP_HDR_OP_OFS] != (NATPMP_RESPONSE | NATPMP_OP_GETEXTERNAL)) {
336 : 0 : LogWarning("natpmp: Response to wrong command\n");
337 : 0 : return false; // Wasn't response to what we expected, try receiving next packet.
338 : : }
339 : : return true;
340 : : },
341 [ + - ]: 3 : interrupt);
342 : :
343 : 3 : struct in_addr external_addr;
344 [ + - ]: 3 : if (recv_res) {
345 [ - + ]: 3 : const std::span<const uint8_t> response = *recv_res;
346 : :
347 [ + + ]: 3 : Assume(response.size() >= NATPMP_GETEXTERNAL_RESPONSE_SIZE);
348 [ + + ]: 3 : uint16_t result_code = ReadBE16(response.data() + NATPMP_RESPONSE_HDR_RESULT_OFS);
349 [ + + ]: 3 : if (result_code != NATPMP_RESULT_SUCCESS) {
350 [ + - + - ]: 1 : LogWarning("natpmp: Getting external address failed with result %s\n", NATPMPResultString(result_code));
351 : 1 : return MappingError::PROTOCOL_ERROR;
352 : : }
353 : :
354 [ + - ]: 2 : std::memcpy(&external_addr, response.data() + NATPMP_GETEXTERNAL_RESPONSE_IP_OFS, ADDR_IPV4_SIZE);
355 : : } else {
356 : 0 : return MappingError::NETWORK_ERROR;
357 : : }
358 : :
359 : : // Create TCP mapping request (RFC6886 section 3.3).
360 [ + - ]: 4 : request = std::vector<uint8_t>(NATPMP_MAP_REQUEST_SIZE);
361 : 2 : request[NATPMP_HDR_VERSION_OFS] = NATPMP_VERSION;
362 : 2 : request[NATPMP_HDR_OP_OFS] = NATPMP_REQUEST | NATPMP_OP_MAP_TCP;
363 : 2 : WriteBE16(request.data() + NATPMP_MAP_REQUEST_INTERNAL_PORT_OFS, port);
364 : 2 : WriteBE16(request.data() + NATPMP_MAP_REQUEST_EXTERNAL_PORT_OFS, port);
365 : 2 : WriteBE32(request.data() + NATPMP_MAP_REQUEST_LIFETIME_OFS, lifetime);
366 : :
367 [ + - + - ]: 4 : recv_res = PCPSendRecv(*sock, "natpmp", request, num_tries, timeout_per_try,
368 [ - + ]: 2 : [&](const std::span<const uint8_t> response) -> bool {
369 [ - + ]: 2 : if (response.size() < NATPMP_MAP_RESPONSE_SIZE) {
370 : 0 : LogWarning("natpmp: Response too small\n");
371 : 0 : return false; // Wasn't response to what we expected, try receiving next packet.
372 : : }
373 [ + - - + ]: 2 : if (response[0] != NATPMP_VERSION || response[1] != (NATPMP_RESPONSE | NATPMP_OP_MAP_TCP)) {
374 : 0 : LogWarning("natpmp: Response to wrong command\n");
375 : 0 : return false; // Wasn't response to what we expected, try receiving next packet.
376 : : }
377 [ - + ]: 2 : uint16_t internal_port = ReadBE16(response.data() + NATPMP_MAP_RESPONSE_INTERNAL_PORT_OFS);
378 [ - + ]: 2 : if (internal_port != port) {
379 : 0 : LogWarning("natpmp: Response port doesn't match request\n");
380 : 0 : return false; // Wasn't response to what we expected, try receiving next packet.
381 : : }
382 : : return true;
383 : : },
384 : 2 : interrupt);
385 : :
386 [ + - ]: 2 : if (recv_res) {
387 [ - + ]: 2 : const std::span<uint8_t> response = *recv_res;
388 : :
389 [ + + ]: 2 : Assume(response.size() >= NATPMP_MAP_RESPONSE_SIZE);
390 [ + + ]: 2 : uint16_t result_code = ReadBE16(response.data() + NATPMP_RESPONSE_HDR_RESULT_OFS);
391 [ + + ]: 2 : if (result_code != NATPMP_RESULT_SUCCESS) {
392 [ - + ]: 1 : if (result_code == NATPMP_RESULT_NOT_AUTHORIZED) {
393 [ # # # # : 0 : LogWarnThenDebug(BCLog::NET, "natpmp: Port mapping failed with result %s", NATPMPResultString(result_code));
# # # # #
# # # #
# ]
394 : : } else {
395 [ + - + - ]: 1 : LogWarning("natpmp: Port mapping failed with result %s", NATPMPResultString(result_code));
396 : : }
397 [ - + ]: 1 : if (result_code == NATPMP_RESULT_NO_RESOURCES) {
398 : 0 : return MappingError::NO_RESOURCES;
399 : : }
400 : 1 : return MappingError::PROTOCOL_ERROR;
401 : : }
402 : :
403 [ + - ]: 1 : uint32_t lifetime_ret = ReadBE32(response.data() + NATPMP_MAP_RESPONSE_LIFETIME_OFS);
404 [ + - ]: 1 : uint16_t external_port = ReadBE16(response.data() + NATPMP_MAP_RESPONSE_EXTERNAL_PORT_OFS);
405 [ + - + - ]: 2 : return MappingResult(NATPMP_VERSION, CService(internal.sin_addr, port), CService(external_addr, external_port), lifetime_ret);
406 : : } else {
407 : 0 : return MappingError::NETWORK_ERROR;
408 : : }
409 : 3 : }
410 : :
411 : 8 : std::variant<MappingResult, MappingError> PCPRequestPortMap(const PCPMappingNonce &nonce, const CNetAddr &gateway, const CNetAddr &bind, uint16_t port, uint32_t lifetime, CThreadInterrupt& interrupt, int num_tries, std::chrono::milliseconds timeout_per_try)
412 : : {
413 : 8 : struct sockaddr_storage dest_addr, bind_addr;
414 : 8 : socklen_t dest_addrlen = sizeof(struct sockaddr_storage), bind_addrlen = sizeof(struct sockaddr_storage);
415 : :
416 [ + - + - : 8 : LogDebug(BCLog::NET, "pcp: Requesting port mapping for addr %s port %d from gateway %s\n", bind.ToStringAddr(), port, gateway.ToStringAddr());
+ - ]
417 : :
418 : : // Validate addresses, make sure they're the same network family.
419 [ + - - + ]: 8 : if (!CService(gateway, PCP_SERVER_PORT).GetSockAddr((struct sockaddr*)&dest_addr, &dest_addrlen)) return MappingError::NETWORK_ERROR;
420 [ + - - + ]: 8 : if (!CService(bind, 0).GetSockAddr((struct sockaddr*)&bind_addr, &bind_addrlen)) return MappingError::NETWORK_ERROR;
421 [ - + ]: 8 : if (dest_addr.ss_family != bind_addr.ss_family) return MappingError::NETWORK_ERROR;
422 : :
423 : : // Create UDP socket (IPv4 or IPv6 based on provided gateway).
424 : 8 : auto sock{CreateSock(dest_addr.ss_family, SOCK_DGRAM, IPPROTO_UDP)};
425 [ - + ]: 8 : if (!sock) {
426 [ # # # # ]: 0 : LogWarning("pcp: Could not create UDP socket: %s\n", NetworkErrorString(WSAGetLastError()));
427 : 0 : return MappingError::NETWORK_ERROR;
428 : : }
429 : :
430 : : // Make sure that we send from requested destination address, anything else will be
431 : : // rejected by a security-conscious router.
432 [ + - - + ]: 8 : if (sock->Bind((struct sockaddr*)&bind_addr, bind_addrlen) != 0) {
433 [ # # # # ]: 0 : LogWarning("pcp: Could not bind to address: %s\n", NetworkErrorString(WSAGetLastError()));
434 : 0 : return MappingError::NETWORK_ERROR;
435 : : }
436 : :
437 : : // Associate UDP socket to gateway.
438 [ + - - + ]: 8 : if (sock->Connect((struct sockaddr*)&dest_addr, dest_addrlen) != 0) {
439 [ # # # # ]: 0 : LogWarning("pcp: Could not connect to gateway: %s\n", NetworkErrorString(WSAGetLastError()));
440 : 0 : return MappingError::NETWORK_ERROR;
441 : : }
442 : :
443 : : // Use getsockname to get the address toward the default gateway (the internal address),
444 : : // in case we don't know what address to map
445 : : // (this is only needed if bind is INADDR_ANY, but it doesn't hurt as an extra check).
446 : 8 : struct sockaddr_storage internal_addr;
447 : 8 : socklen_t internal_addrlen = sizeof(struct sockaddr_storage);
448 [ + - - + ]: 8 : if (sock->GetSockName((struct sockaddr*)&internal_addr, &internal_addrlen) != 0) {
449 [ # # # # ]: 0 : LogWarning("pcp: Could not get sock name: %s\n", NetworkErrorString(WSAGetLastError()));
450 : 0 : return MappingError::NETWORK_ERROR;
451 : : }
452 [ + - ]: 8 : CService internal;
453 [ + - - + ]: 8 : if (!internal.SetSockAddr((struct sockaddr*)&internal_addr, internal_addrlen)) return MappingError::NETWORK_ERROR;
454 [ + - + - : 8 : LogDebug(BCLog::NET, "pcp: Internal address after connect: %s\n", internal.ToStringAddr());
+ - + - ]
455 : :
456 : : // Build request packet. Make sure the packet is zeroed so that reserved fields are zero
457 : : // as required by the spec (and not potentially leak data).
458 : : // Make sure there's space for the request header and MAP specific request data.
459 [ + - ]: 8 : std::vector<uint8_t> request(PCP_HDR_SIZE + PCP_MAP_SIZE);
460 : : // Fill in request header, See RFC6887 Figure 2.
461 : 8 : size_t ofs = 0;
462 : 8 : request[ofs + PCP_HDR_VERSION_OFS] = PCP_VERSION;
463 : 8 : request[ofs + PCP_HDR_OP_OFS] = PCP_REQUEST | PCP_OP_MAP;
464 : 8 : WriteBE32(request.data() + ofs + PCP_HDR_LIFETIME_OFS, lifetime);
465 [ - + + - : 8 : if (!PCPWrapAddress(std::span(request).subspan(ofs + PCP_REQUEST_HDR_IP_OFS, ADDR_IPV6_SIZE), internal)) return MappingError::NETWORK_ERROR;
- + ]
466 : :
467 : 8 : ofs += PCP_HDR_SIZE;
468 : :
469 : : // Fill in MAP request packet, See RFC6887 Figure 9.
470 : : // Randomize mapping nonce (this is repeated in the response, to be able to
471 : : // correlate requests and responses, and used to authenticate changes to the mapping).
472 : 8 : std::memcpy(request.data() + ofs + PCP_MAP_NONCE_OFS, nonce.data(), PCP_MAP_NONCE_SIZE);
473 : 8 : request[ofs + PCP_MAP_PROTOCOL_OFS] = PCP_PROTOCOL_TCP;
474 : 8 : WriteBE16(request.data() + ofs + PCP_MAP_INTERNAL_PORT_OFS, port);
475 : 8 : WriteBE16(request.data() + ofs + PCP_MAP_EXTERNAL_PORT_OFS, port);
476 [ - + + - : 8 : if (!PCPWrapAddress(std::span(request).subspan(ofs + PCP_MAP_EXTERNAL_IP_OFS, ADDR_IPV6_SIZE), bind)) return MappingError::NETWORK_ERROR;
- + ]
477 : :
478 : 8 : ofs += PCP_MAP_SIZE;
479 [ - + + - ]: 8 : Assume(ofs == request.size());
480 : :
481 : : // Receive loop.
482 : 8 : bool is_natpmp = false;
483 [ + - ]: 16 : auto recv_res = PCPSendRecv(*sock, "pcp", request, num_tries, timeout_per_try,
484 [ + - ]: 8 : [&](const std::span<const uint8_t> response) -> bool {
485 : : // Unsupported version according to RFC6887 appendix A and RFC6886 section 3.5, can fall back to NAT-PMP.
486 [ + + + - : 6 : if (response.size() == NATPMP_RESPONSE_HDR_SIZE && response[PCP_HDR_VERSION_OFS] == NATPMP_VERSION && response[PCP_RESPONSE_HDR_RESULT_OFS] == NATPMP_RESULT_UNSUPP_VERSION) {
+ - ]
487 : 1 : is_natpmp = true;
488 : 1 : return true; // Let it through to caller.
489 : : }
490 [ - + ]: 5 : if (response.size() < (PCP_HDR_SIZE + PCP_MAP_SIZE)) {
491 : 0 : LogWarning("pcp: Response too small\n");
492 : 0 : return false; // Wasn't response to what we expected, try receiving next packet.
493 : : }
494 [ + - + - ]: 5 : if (response[PCP_HDR_VERSION_OFS] != PCP_VERSION || response[PCP_HDR_OP_OFS] != (PCP_RESPONSE | PCP_OP_MAP)) {
495 : 0 : LogWarning("pcp: Response to wrong command\n");
496 : 0 : return false; // Wasn't response to what we expected, try receiving next packet.
497 : : }
498 : : // Handle MAP opcode response. See RFC6887 Figure 10.
499 : : // Check that returned mapping nonce matches our request.
500 [ - + ]: 5 : if (!std::ranges::equal(response.subspan(PCP_HDR_SIZE + PCP_MAP_NONCE_OFS, PCP_MAP_NONCE_SIZE), nonce)) {
501 : 0 : LogWarning("pcp: Mapping nonce mismatch\n");
502 : 0 : return false; // Wasn't response to what we expected, try receiving next packet.
503 : : }
504 : 5 : uint8_t protocol = response[PCP_HDR_SIZE + 12];
505 [ + - ]: 5 : uint16_t internal_port = ReadBE16(response.data() + PCP_HDR_SIZE + 16);
506 [ + - - + ]: 5 : if (protocol != PCP_PROTOCOL_TCP || internal_port != port) {
507 : 0 : LogWarning("pcp: Response protocol or port doesn't match request\n");
508 : 0 : return false; // Wasn't response to what we expected, try receiving next packet.
509 : : }
510 : : return true;
511 : : },
512 [ + - ]: 8 : interrupt);
513 : :
514 [ + + ]: 8 : if (!recv_res) {
515 : 2 : return MappingError::NETWORK_ERROR;
516 : : }
517 [ + + ]: 6 : if (is_natpmp) {
518 : 1 : return MappingError::UNSUPP_VERSION;
519 : : }
520 : :
521 [ - + ]: 5 : const std::span<const uint8_t> response = *recv_res;
522 : : // If we get here, we got a valid MAP response to our request.
523 : : // Check to see if we got the result we expected.
524 [ + - ]: 5 : Assume(response.size() >= (PCP_HDR_SIZE + PCP_MAP_SIZE));
525 : 5 : uint8_t result_code = response[PCP_RESPONSE_HDR_RESULT_OFS];
526 [ + - ]: 5 : uint32_t lifetime_ret = ReadBE32(response.data() + PCP_HDR_LIFETIME_OFS);
527 [ + - ]: 5 : uint16_t external_port = ReadBE16(response.data() + PCP_HDR_SIZE + PCP_MAP_EXTERNAL_PORT_OFS);
528 [ + - ]: 5 : CNetAddr external_addr{PCPUnwrapAddress(response.subspan(PCP_HDR_SIZE + PCP_MAP_EXTERNAL_IP_OFS, ADDR_IPV6_SIZE))};
529 [ + + ]: 5 : if (result_code != PCP_RESULT_SUCCESS) {
530 [ - + ]: 2 : if (result_code == PCP_RESULT_NOT_AUTHORIZED) {
531 [ # # # # : 0 : LogWarnThenDebug(BCLog::NET, "pcp: Mapping failed with result %s", PCPResultString(result_code));
# # # # #
# # # #
# ]
532 : : } else {
533 [ + - + - ]: 2 : LogWarning("pcp: Mapping failed with result %s", PCPResultString(result_code));
534 : : }
535 [ + + ]: 2 : if (result_code == PCP_RESULT_NO_RESOURCES) {
536 : 1 : return MappingError::NO_RESOURCES;
537 : : }
538 : 1 : return MappingError::PROTOCOL_ERROR;
539 : : }
540 : :
541 [ + - + - ]: 6 : return MappingResult(PCP_VERSION, CService(internal, port), CService(external_addr, external_port), lifetime_ret);
542 : 29 : }
543 : :
544 : 0 : std::string MappingResult::ToString() const
545 : : {
546 : 0 : Assume(version == NATPMP_VERSION || version == PCP_VERSION);
547 : 0 : return strprintf("%s:%s -> %s (for %ds)",
548 [ # # ]: 0 : version == NATPMP_VERSION ? "natpmp" : "pcp",
549 [ # # ]: 0 : external.ToStringAddrPort(),
550 : 0 : internal.ToStringAddrPort(),
551 : 0 : lifetime
552 [ # # ]: 0 : );
553 : : }
|