SOCKSProxyClient.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/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::Stream::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. auto size = TRY(socket.write({ &message, sizeof(message) }));
  93. if (size != sizeof(message))
  94. return Error::from_string_literal("SOCKS negotiation failed: Failed to send version identifier and method selection message");
  95. Socks5InitialResponse response;
  96. size = TRY(socket.read({ &response, sizeof(response) })).size();
  97. if (size != sizeof(response))
  98. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive initial response");
  99. if (response.version_identifier != to_underlying(version))
  100. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  101. if (response.method != to_underlying(method))
  102. return Error::from_string_literal("SOCKS negotiation failed: Failed to negotiate a method");
  103. return {};
  104. }
  105. ErrorOr<Reply> send_connect_request_message(Core::Stream::Socket& socket, Core::SOCKSProxyClient::Version version, Core::SOCKSProxyClient::HostOrIPV4 target, int port, Core::SOCKSProxyClient::Command command)
  106. {
  107. Core::Stream::AllocatingMemoryStream stream;
  108. Socks5ConnectRequestHeader header {
  109. .version_identifier = to_underlying(version),
  110. .command = to_underlying(command),
  111. .reserved = 0,
  112. };
  113. Socks5ConnectRequestTrailer trailer {
  114. .port = htons(port),
  115. };
  116. auto size = TRY(stream.write({ &header, sizeof(header) }));
  117. if (size != sizeof(header))
  118. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request header");
  119. TRY(target.visit(
  120. [&](DeprecatedString const& hostname) -> ErrorOr<void> {
  121. u8 address_data[2];
  122. address_data[0] = to_underlying(AddressType::DomainName);
  123. address_data[1] = hostname.length();
  124. auto size = TRY(stream.write({ address_data, sizeof(address_data) }));
  125. if (size != array_size(address_data))
  126. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request address data");
  127. TRY(stream.write({ hostname.characters(), hostname.length() }));
  128. return {};
  129. },
  130. [&](u32 ipv4) -> ErrorOr<void> {
  131. u8 address_data[5];
  132. address_data[0] = to_underlying(AddressType::IPV4);
  133. u32 network_ordered_ipv4 = NetworkOrdered<u32>(ipv4);
  134. memcpy(address_data + 1, &network_ordered_ipv4, sizeof(network_ordered_ipv4));
  135. auto size = TRY(stream.write({ address_data, sizeof(address_data) }));
  136. if (size != array_size(address_data))
  137. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request address data");
  138. return {};
  139. }));
  140. size = TRY(stream.write({ &trailer, sizeof(trailer) }));
  141. if (size != sizeof(trailer))
  142. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request trailer");
  143. auto buffer = TRY(ByteBuffer::create_uninitialized(stream.used_buffer_size()));
  144. TRY(stream.read_entire_buffer(buffer.bytes()));
  145. size = TRY(socket.write({ buffer.data(), buffer.size() }));
  146. if (size != buffer.size())
  147. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request");
  148. Socks5ConnectResponseHeader response_header;
  149. size = TRY(socket.read({ &response_header, sizeof(response_header) })).size();
  150. if (size != sizeof(response_header))
  151. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response header");
  152. if (response_header.version_identifier != to_underlying(version))
  153. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  154. u8 response_address_type;
  155. size = TRY(socket.read({ &response_address_type, sizeof(response_address_type) })).size();
  156. if (size != sizeof(response_address_type))
  157. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address type");
  158. switch (AddressType(response_address_type)) {
  159. case AddressType::IPV4: {
  160. u8 response_address_data[4];
  161. size = TRY(socket.read({ response_address_data, sizeof(response_address_data) })).size();
  162. if (size != sizeof(response_address_data))
  163. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address data");
  164. break;
  165. }
  166. case AddressType::DomainName: {
  167. u8 response_address_length;
  168. size = TRY(socket.read({ &response_address_length, sizeof(response_address_length) })).size();
  169. if (size != sizeof(response_address_length))
  170. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address length");
  171. ByteBuffer buffer;
  172. buffer.resize(response_address_length);
  173. size = TRY(socket.read(buffer)).size();
  174. if (size != response_address_length)
  175. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address data");
  176. break;
  177. }
  178. case AddressType::IPV6:
  179. default:
  180. return Error::from_string_literal("SOCKS negotiation failed: Invalid connect response address type");
  181. }
  182. u16 bound_port;
  183. size = TRY(socket.read({ &bound_port, sizeof(bound_port) })).size();
  184. if (size != sizeof(bound_port))
  185. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response bound port");
  186. return Reply(response_header.status);
  187. }
  188. ErrorOr<u8> send_username_password_authentication_message(Core::Stream::Socket& socket, Core::SOCKSProxyClient::UsernamePasswordAuthenticationData const& auth_data)
  189. {
  190. Core::Stream::AllocatingMemoryStream stream;
  191. u8 version = 0x01;
  192. auto size = TRY(stream.write({ &version, sizeof(version) }));
  193. if (size != sizeof(version))
  194. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  195. u8 username_length = auth_data.username.length();
  196. size = TRY(stream.write({ &username_length, sizeof(username_length) }));
  197. if (size != sizeof(username_length))
  198. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  199. size = TRY(stream.write({ auth_data.username.characters(), auth_data.username.length() }));
  200. if (size != auth_data.username.length())
  201. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  202. u8 password_length = auth_data.password.length();
  203. size = TRY(stream.write({ &password_length, sizeof(password_length) }));
  204. if (size != sizeof(password_length))
  205. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  206. size = TRY(stream.write({ auth_data.password.characters(), auth_data.password.length() }));
  207. if (size != auth_data.password.length())
  208. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  209. auto buffer = TRY(ByteBuffer::create_uninitialized(stream.used_buffer_size()));
  210. TRY(stream.read_entire_buffer(buffer.bytes()));
  211. size = TRY(socket.write(buffer));
  212. if (size != buffer.size())
  213. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  214. Socks5UsernamePasswordResponse response;
  215. size = TRY(socket.read({ &response, sizeof(response) })).size();
  216. if (size != sizeof(response))
  217. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive username/password authentication response");
  218. if (response.version_identifier != version)
  219. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  220. return response.status;
  221. }
  222. }
  223. namespace Core {
  224. SOCKSProxyClient::~SOCKSProxyClient()
  225. {
  226. close();
  227. m_socket.on_ready_to_read = nullptr;
  228. }
  229. ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> SOCKSProxyClient::connect(Socket& underlying, Version version, HostOrIPV4 const& target, int target_port, Variant<UsernamePasswordAuthenticationData, Empty> const& auth_data, Command command)
  230. {
  231. if (version != Version::V5)
  232. return Error::from_string_literal("SOCKS version not supported");
  233. return auth_data.visit(
  234. [&](Empty) -> ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> {
  235. TRY(send_version_identifier_and_method_selection_message(underlying, version, Method::NoAuth));
  236. auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
  237. if (reply != Reply::Succeeded) {
  238. underlying.close();
  239. return Error::from_string_view(reply_response_name(reply));
  240. }
  241. return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {
  242. underlying,
  243. nullptr,
  244. });
  245. },
  246. [&](UsernamePasswordAuthenticationData const& auth_data) -> ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> {
  247. TRY(send_version_identifier_and_method_selection_message(underlying, version, Method::UsernamePassword));
  248. auto auth_response = TRY(send_username_password_authentication_message(underlying, auth_data));
  249. if (auth_response != 0) {
  250. underlying.close();
  251. return Error::from_string_literal("SOCKS authentication failed");
  252. }
  253. auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
  254. if (reply != Reply::Succeeded) {
  255. underlying.close();
  256. return Error::from_string_view(reply_response_name(reply));
  257. }
  258. return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {
  259. underlying,
  260. nullptr,
  261. });
  262. });
  263. }
  264. 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)
  265. {
  266. auto underlying = TRY(server.visit(
  267. [&](u32 ipv4) {
  268. return Core::Stream::TCPSocket::connect({ IPv4Address(ipv4), static_cast<u16>(server_port) });
  269. },
  270. [&](DeprecatedString const& hostname) {
  271. return Core::Stream::TCPSocket::connect(hostname, static_cast<u16>(server_port));
  272. }));
  273. auto socket = TRY(connect(*underlying, version, target, target_port, auth_data, command));
  274. socket->m_own_underlying_socket = move(underlying);
  275. dbgln("SOCKS proxy connected, have {} available bytes", TRY(socket->m_socket.pending_bytes()));
  276. return socket;
  277. }
  278. }