SOCKSProxyClient.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /*
  2. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/MemoryStream.h>
  7. #include <LibCore/SOCKSProxyClient.h>
  8. enum class Method : u8 {
  9. NoAuth = 0x00,
  10. GSSAPI = 0x01,
  11. UsernamePassword = 0x02,
  12. NoAcceptableMethods = 0xFF,
  13. };
  14. enum class AddressType : u8 {
  15. IPV4 = 0x01,
  16. DomainName = 0x03,
  17. IPV6 = 0x04,
  18. };
  19. enum class Reply {
  20. Succeeded = 0x00,
  21. GeneralSocksServerFailure = 0x01,
  22. ConnectionNotAllowedByRuleset = 0x02,
  23. NetworkUnreachable = 0x03,
  24. HostUnreachable = 0x04,
  25. ConnectionRefused = 0x05,
  26. TTLExpired = 0x06,
  27. CommandNotSupported = 0x07,
  28. AddressTypeNotSupported = 0x08,
  29. };
  30. struct [[gnu::packed]] Socks5VersionIdentifierAndMethodSelectionMessage {
  31. u8 version_identifier;
  32. u8 method_count;
  33. // NOTE: We only send a single method, so we don't need to make this variable-length.
  34. u8 methods[1];
  35. };
  36. struct [[gnu::packed]] Socks5InitialResponse {
  37. u8 version_identifier;
  38. u8 method;
  39. };
  40. struct [[gnu::packed]] Socks5ConnectRequestHeader {
  41. u8 version_identifier;
  42. u8 command;
  43. u8 reserved;
  44. };
  45. struct [[gnu::packed]] Socks5ConnectRequestTrailer {
  46. u16 port;
  47. };
  48. struct [[gnu::packed]] Socks5ConnectResponseHeader {
  49. u8 version_identifier;
  50. u8 status;
  51. u8 reserved;
  52. };
  53. struct [[gnu::packed]] Socks5ConnectResponseTrailer {
  54. u8 bind_port;
  55. };
  56. struct [[gnu::packed]] Socks5UsernamePasswordResponse {
  57. u8 version_identifier;
  58. u8 status;
  59. };
  60. namespace {
  61. StringView reply_response_name(Reply reply)
  62. {
  63. switch (reply) {
  64. case Reply::Succeeded:
  65. return "Succeeded"sv;
  66. case Reply::GeneralSocksServerFailure:
  67. return "GeneralSocksServerFailure"sv;
  68. case Reply::ConnectionNotAllowedByRuleset:
  69. return "ConnectionNotAllowedByRuleset"sv;
  70. case Reply::NetworkUnreachable:
  71. return "NetworkUnreachable"sv;
  72. case Reply::HostUnreachable:
  73. return "HostUnreachable"sv;
  74. case Reply::ConnectionRefused:
  75. return "ConnectionRefused"sv;
  76. case Reply::TTLExpired:
  77. return "TTLExpired"sv;
  78. case Reply::CommandNotSupported:
  79. return "CommandNotSupported"sv;
  80. case Reply::AddressTypeNotSupported:
  81. return "AddressTypeNotSupported"sv;
  82. }
  83. VERIFY_NOT_REACHED();
  84. }
  85. ErrorOr<void> send_version_identifier_and_method_selection_message(Core::Socket& socket, Core::SOCKSProxyClient::Version version, Method method)
  86. {
  87. Socks5VersionIdentifierAndMethodSelectionMessage message {
  88. .version_identifier = to_underlying(version),
  89. .method_count = 1,
  90. .methods = { to_underlying(method) },
  91. };
  92. // FIXME: This should write the entire span.
  93. auto size = TRY(socket.write_some({ &message, sizeof(message) }));
  94. if (size != sizeof(message))
  95. return Error::from_string_literal("SOCKS negotiation failed: Failed to send version identifier and method selection message");
  96. Socks5InitialResponse response;
  97. // FIXME: This should read the entire span.
  98. size = TRY(socket.read_some({ &response, sizeof(response) })).size();
  99. if (size != sizeof(response))
  100. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive initial response");
  101. if (response.version_identifier != to_underlying(version))
  102. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  103. if (response.method != to_underlying(method))
  104. return Error::from_string_literal("SOCKS negotiation failed: Failed to negotiate a method");
  105. return {};
  106. }
  107. ErrorOr<Reply> send_connect_request_message(Core::Socket& socket, Core::SOCKSProxyClient::Version version, Core::SOCKSProxyClient::HostOrIPV4 target, int port, Core::SOCKSProxyClient::Command command)
  108. {
  109. AllocatingMemoryStream stream;
  110. Socks5ConnectRequestHeader header {
  111. .version_identifier = to_underlying(version),
  112. .command = to_underlying(command),
  113. .reserved = 0,
  114. };
  115. Socks5ConnectRequestTrailer trailer {
  116. .port = htons(port),
  117. };
  118. // FIXME: This should write the entire span.
  119. auto size = TRY(stream.write_some({ &header, sizeof(header) }));
  120. if (size != sizeof(header))
  121. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request header");
  122. TRY(target.visit(
  123. [&](DeprecatedString const& hostname) -> ErrorOr<void> {
  124. u8 address_data[2];
  125. address_data[0] = to_underlying(AddressType::DomainName);
  126. address_data[1] = hostname.length();
  127. // FIXME: This should write the entire span.
  128. auto size = TRY(stream.write_some({ address_data, sizeof(address_data) }));
  129. if (size != array_size(address_data))
  130. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request address data");
  131. // FIXME: This should write the entire span.
  132. TRY(stream.write_some({ hostname.characters(), hostname.length() }));
  133. return {};
  134. },
  135. [&](u32 ipv4) -> ErrorOr<void> {
  136. u8 address_data[5];
  137. address_data[0] = to_underlying(AddressType::IPV4);
  138. u32 network_ordered_ipv4 = NetworkOrdered<u32>(ipv4);
  139. memcpy(address_data + 1, &network_ordered_ipv4, sizeof(network_ordered_ipv4));
  140. // FIXME: This should write the entire span.
  141. auto size = TRY(stream.write_some({ address_data, sizeof(address_data) }));
  142. if (size != array_size(address_data))
  143. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request address data");
  144. return {};
  145. }));
  146. // FIXME: This should write the entire span.
  147. size = TRY(stream.write_some({ &trailer, sizeof(trailer) }));
  148. if (size != sizeof(trailer))
  149. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request trailer");
  150. auto buffer = TRY(ByteBuffer::create_uninitialized(stream.used_buffer_size()));
  151. TRY(stream.read_entire_buffer(buffer.bytes()));
  152. // FIXME: This should write the entire span.
  153. size = TRY(socket.write_some({ buffer.data(), buffer.size() }));
  154. if (size != buffer.size())
  155. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request");
  156. Socks5ConnectResponseHeader response_header;
  157. // FIXME: This should read the entire span.
  158. size = TRY(socket.read_some({ &response_header, sizeof(response_header) })).size();
  159. if (size != sizeof(response_header))
  160. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response header");
  161. if (response_header.version_identifier != to_underlying(version))
  162. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  163. u8 response_address_type;
  164. // FIXME: This should read the entire span.
  165. size = TRY(socket.read_some({ &response_address_type, sizeof(response_address_type) })).size();
  166. if (size != sizeof(response_address_type))
  167. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address type");
  168. switch (AddressType(response_address_type)) {
  169. case AddressType::IPV4: {
  170. u8 response_address_data[4];
  171. // FIXME: This should read the entire span.
  172. size = TRY(socket.read_some({ response_address_data, sizeof(response_address_data) })).size();
  173. if (size != sizeof(response_address_data))
  174. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address data");
  175. break;
  176. }
  177. case AddressType::DomainName: {
  178. u8 response_address_length;
  179. // FIXME: This should read the entire span.
  180. size = TRY(socket.read_some({ &response_address_length, sizeof(response_address_length) })).size();
  181. if (size != sizeof(response_address_length))
  182. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address length");
  183. ByteBuffer buffer;
  184. buffer.resize(response_address_length);
  185. // FIXME: This should read the entire span.
  186. size = TRY(socket.read_some(buffer)).size();
  187. if (size != response_address_length)
  188. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address data");
  189. break;
  190. }
  191. case AddressType::IPV6:
  192. default:
  193. return Error::from_string_literal("SOCKS negotiation failed: Invalid connect response address type");
  194. }
  195. u16 bound_port;
  196. // FIXME: This should read the entire span.
  197. size = TRY(socket.read_some({ &bound_port, sizeof(bound_port) })).size();
  198. if (size != sizeof(bound_port))
  199. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response bound port");
  200. return Reply(response_header.status);
  201. }
  202. ErrorOr<u8> send_username_password_authentication_message(Core::Socket& socket, Core::SOCKSProxyClient::UsernamePasswordAuthenticationData const& auth_data)
  203. {
  204. AllocatingMemoryStream stream;
  205. u8 version = 0x01;
  206. // FIXME: This should write the entire span.
  207. auto size = TRY(stream.write_some({ &version, sizeof(version) }));
  208. if (size != sizeof(version))
  209. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  210. u8 username_length = auth_data.username.length();
  211. // FIXME: This should write the entire span.
  212. size = TRY(stream.write_some({ &username_length, sizeof(username_length) }));
  213. if (size != sizeof(username_length))
  214. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  215. // FIXME: This should write the entire span.
  216. size = TRY(stream.write_some({ auth_data.username.characters(), auth_data.username.length() }));
  217. if (size != auth_data.username.length())
  218. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  219. u8 password_length = auth_data.password.length();
  220. // FIXME: This should write the entire span.
  221. size = TRY(stream.write_some({ &password_length, sizeof(password_length) }));
  222. if (size != sizeof(password_length))
  223. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  224. // FIXME: This should write the entire span.
  225. size = TRY(stream.write_some({ auth_data.password.characters(), auth_data.password.length() }));
  226. if (size != auth_data.password.length())
  227. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  228. auto buffer = TRY(ByteBuffer::create_uninitialized(stream.used_buffer_size()));
  229. TRY(stream.read_entire_buffer(buffer.bytes()));
  230. // FIXME: This should write the entire span.
  231. size = TRY(socket.write_some(buffer));
  232. if (size != buffer.size())
  233. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  234. Socks5UsernamePasswordResponse response;
  235. // FIXME: This should read the entire span.
  236. size = TRY(socket.read_some({ &response, sizeof(response) })).size();
  237. if (size != sizeof(response))
  238. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive username/password authentication response");
  239. if (response.version_identifier != version)
  240. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  241. return response.status;
  242. }
  243. }
  244. namespace Core {
  245. SOCKSProxyClient::~SOCKSProxyClient()
  246. {
  247. close();
  248. m_socket.on_ready_to_read = nullptr;
  249. }
  250. ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> SOCKSProxyClient::connect(Socket& underlying, Version version, HostOrIPV4 const& target, int target_port, Variant<UsernamePasswordAuthenticationData, Empty> const& auth_data, Command command)
  251. {
  252. if (version != Version::V5)
  253. return Error::from_string_literal("SOCKS version not supported");
  254. return auth_data.visit(
  255. [&](Empty) -> ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> {
  256. TRY(send_version_identifier_and_method_selection_message(underlying, version, Method::NoAuth));
  257. auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
  258. if (reply != Reply::Succeeded) {
  259. underlying.close();
  260. return Error::from_string_view(reply_response_name(reply));
  261. }
  262. return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {
  263. underlying,
  264. nullptr,
  265. });
  266. },
  267. [&](UsernamePasswordAuthenticationData const& auth_data) -> ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> {
  268. TRY(send_version_identifier_and_method_selection_message(underlying, version, Method::UsernamePassword));
  269. auto auth_response = TRY(send_username_password_authentication_message(underlying, auth_data));
  270. if (auth_response != 0) {
  271. underlying.close();
  272. return Error::from_string_literal("SOCKS authentication failed");
  273. }
  274. auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
  275. if (reply != Reply::Succeeded) {
  276. underlying.close();
  277. return Error::from_string_view(reply_response_name(reply));
  278. }
  279. return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {
  280. underlying,
  281. nullptr,
  282. });
  283. });
  284. }
  285. ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> SOCKSProxyClient::connect(HostOrIPV4 const& server, int server_port, Version version, HostOrIPV4 const& target, int target_port, Variant<UsernamePasswordAuthenticationData, Empty> const& auth_data, Command command)
  286. {
  287. auto underlying = TRY(server.visit(
  288. [&](u32 ipv4) {
  289. return Core::TCPSocket::connect({ IPv4Address(ipv4), static_cast<u16>(server_port) });
  290. },
  291. [&](DeprecatedString const& hostname) {
  292. return Core::TCPSocket::connect(hostname, static_cast<u16>(server_port));
  293. }));
  294. auto socket = TRY(connect(*underlying, version, target, target_port, auth_data, command));
  295. socket->m_own_underlying_socket = move(underlying);
  296. dbgln("SOCKS proxy connected, have {} available bytes", TRY(socket->m_socket.pending_bytes()));
  297. return socket;
  298. }
  299. }