SOCKSProxyClient.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. template<>
  37. struct AK::Traits<Socks5VersionIdentifierAndMethodSelectionMessage> : public AK::DefaultTraits<Socks5VersionIdentifierAndMethodSelectionMessage> {
  38. static constexpr bool is_trivially_serializable() { return true; }
  39. };
  40. struct [[gnu::packed]] Socks5InitialResponse {
  41. u8 version_identifier;
  42. u8 method;
  43. };
  44. template<>
  45. struct AK::Traits<Socks5InitialResponse> : public AK::DefaultTraits<Socks5InitialResponse> {
  46. static constexpr bool is_trivially_serializable() { return true; }
  47. };
  48. struct [[gnu::packed]] Socks5ConnectRequestHeader {
  49. u8 version_identifier;
  50. u8 command;
  51. u8 reserved;
  52. };
  53. template<>
  54. struct AK::Traits<Socks5ConnectRequestHeader> : public AK::DefaultTraits<Socks5ConnectRequestHeader> {
  55. static constexpr bool is_trivially_serializable() { return true; }
  56. };
  57. struct [[gnu::packed]] Socks5ConnectRequestTrailer {
  58. u16 port;
  59. };
  60. template<>
  61. struct AK::Traits<Socks5ConnectRequestTrailer> : public AK::DefaultTraits<Socks5ConnectRequestTrailer> {
  62. static constexpr bool is_trivially_serializable() { return true; }
  63. };
  64. struct [[gnu::packed]] Socks5ConnectResponseHeader {
  65. u8 version_identifier;
  66. u8 status;
  67. u8 reserved;
  68. };
  69. template<>
  70. struct AK::Traits<Socks5ConnectResponseHeader> : public AK::DefaultTraits<Socks5ConnectResponseHeader> {
  71. static constexpr bool is_trivially_serializable() { return true; }
  72. };
  73. struct [[gnu::packed]] Socks5ConnectResponseTrailer {
  74. u8 bind_port;
  75. };
  76. struct [[gnu::packed]] Socks5UsernamePasswordResponse {
  77. u8 version_identifier;
  78. u8 status;
  79. };
  80. template<>
  81. struct AK::Traits<Socks5UsernamePasswordResponse> : public AK::DefaultTraits<Socks5UsernamePasswordResponse> {
  82. static constexpr bool is_trivially_serializable() { return true; }
  83. };
  84. namespace {
  85. StringView reply_response_name(Reply reply)
  86. {
  87. switch (reply) {
  88. case Reply::Succeeded:
  89. return "Succeeded"sv;
  90. case Reply::GeneralSocksServerFailure:
  91. return "GeneralSocksServerFailure"sv;
  92. case Reply::ConnectionNotAllowedByRuleset:
  93. return "ConnectionNotAllowedByRuleset"sv;
  94. case Reply::NetworkUnreachable:
  95. return "NetworkUnreachable"sv;
  96. case Reply::HostUnreachable:
  97. return "HostUnreachable"sv;
  98. case Reply::ConnectionRefused:
  99. return "ConnectionRefused"sv;
  100. case Reply::TTLExpired:
  101. return "TTLExpired"sv;
  102. case Reply::CommandNotSupported:
  103. return "CommandNotSupported"sv;
  104. case Reply::AddressTypeNotSupported:
  105. return "AddressTypeNotSupported"sv;
  106. }
  107. VERIFY_NOT_REACHED();
  108. }
  109. ErrorOr<void> send_version_identifier_and_method_selection_message(Core::Socket& socket, Core::SOCKSProxyClient::Version version, Method method)
  110. {
  111. Socks5VersionIdentifierAndMethodSelectionMessage message {
  112. .version_identifier = to_underlying(version),
  113. .method_count = 1,
  114. .methods = { to_underlying(method) },
  115. };
  116. TRY(socket.write_value(message));
  117. auto response = TRY(socket.read_value<Socks5InitialResponse>());
  118. if (response.version_identifier != to_underlying(version))
  119. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  120. if (response.method != to_underlying(method))
  121. return Error::from_string_literal("SOCKS negotiation failed: Failed to negotiate a method");
  122. return {};
  123. }
  124. ErrorOr<Reply> send_connect_request_message(Core::Socket& socket, Core::SOCKSProxyClient::Version version, Core::SOCKSProxyClient::HostOrIPV4 target, int port, Core::SOCKSProxyClient::Command command)
  125. {
  126. AllocatingMemoryStream stream;
  127. Socks5ConnectRequestHeader header {
  128. .version_identifier = to_underlying(version),
  129. .command = to_underlying(command),
  130. .reserved = 0,
  131. };
  132. Socks5ConnectRequestTrailer trailer {
  133. .port = htons(port),
  134. };
  135. TRY(stream.write_value(header));
  136. TRY(target.visit(
  137. [&](ByteString const& hostname) -> ErrorOr<void> {
  138. u8 address_data[2];
  139. address_data[0] = to_underlying(AddressType::DomainName);
  140. address_data[1] = hostname.length();
  141. TRY(stream.write_until_depleted({ address_data, sizeof(address_data) }));
  142. TRY(stream.write_until_depleted({ hostname.characters(), hostname.length() }));
  143. return {};
  144. },
  145. [&](u32 ipv4) -> ErrorOr<void> {
  146. u8 address_data[5];
  147. address_data[0] = to_underlying(AddressType::IPV4);
  148. u32 network_ordered_ipv4 = NetworkOrdered<u32>(ipv4);
  149. memcpy(address_data + 1, &network_ordered_ipv4, sizeof(network_ordered_ipv4));
  150. TRY(stream.write_until_depleted({ address_data, sizeof(address_data) }));
  151. return {};
  152. }));
  153. TRY(stream.write_value(trailer));
  154. auto buffer = TRY(ByteBuffer::create_uninitialized(stream.used_buffer_size()));
  155. TRY(stream.read_until_filled(buffer.bytes()));
  156. TRY(socket.write_until_depleted(buffer));
  157. auto response_header = TRY(socket.read_value<Socks5ConnectResponseHeader>());
  158. if (response_header.version_identifier != to_underlying(version))
  159. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  160. auto response_address_type = TRY(socket.read_value<u8>());
  161. switch (AddressType(response_address_type)) {
  162. case AddressType::IPV4: {
  163. u8 response_address_data[4];
  164. TRY(socket.read_until_filled({ response_address_data, sizeof(response_address_data) }));
  165. break;
  166. }
  167. case AddressType::DomainName: {
  168. auto response_address_length = TRY(socket.read_value<u8>());
  169. auto buffer = TRY(ByteBuffer::create_uninitialized(response_address_length));
  170. TRY(socket.read_until_filled(buffer));
  171. break;
  172. }
  173. case AddressType::IPV6:
  174. default:
  175. return Error::from_string_literal("SOCKS negotiation failed: Invalid connect response address type");
  176. }
  177. [[maybe_unused]] auto bound_port = TRY(socket.read_value<u16>());
  178. return Reply(response_header.status);
  179. }
  180. ErrorOr<u8> send_username_password_authentication_message(Core::Socket& socket, Core::SOCKSProxyClient::UsernamePasswordAuthenticationData const& auth_data)
  181. {
  182. AllocatingMemoryStream stream;
  183. u8 version = 0x01;
  184. TRY(stream.write_value(version));
  185. u8 username_length = auth_data.username.length();
  186. TRY(stream.write_value(username_length));
  187. TRY(stream.write_until_depleted({ auth_data.username.characters(), auth_data.username.length() }));
  188. u8 password_length = auth_data.password.length();
  189. TRY(stream.write_value(password_length));
  190. TRY(stream.write_until_depleted({ auth_data.password.characters(), auth_data.password.length() }));
  191. auto buffer = TRY(ByteBuffer::create_uninitialized(stream.used_buffer_size()));
  192. TRY(stream.read_until_filled(buffer.bytes()));
  193. TRY(socket.write_until_depleted(buffer));
  194. auto response = TRY(socket.read_value<Socks5UsernamePasswordResponse>());
  195. if (response.version_identifier != version)
  196. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  197. return response.status;
  198. }
  199. }
  200. namespace Core {
  201. SOCKSProxyClient::~SOCKSProxyClient()
  202. {
  203. close();
  204. m_socket.on_ready_to_read = nullptr;
  205. }
  206. ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> SOCKSProxyClient::connect(Socket& underlying, Version version, HostOrIPV4 const& target, int target_port, Variant<UsernamePasswordAuthenticationData, Empty> const& auth_data, Command command)
  207. {
  208. if (version != Version::V5)
  209. return Error::from_string_literal("SOCKS version not supported");
  210. return auth_data.visit(
  211. [&](Empty) -> ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> {
  212. TRY(send_version_identifier_and_method_selection_message(underlying, version, Method::NoAuth));
  213. auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
  214. if (reply != Reply::Succeeded) {
  215. underlying.close();
  216. return Error::from_string_view(reply_response_name(reply));
  217. }
  218. return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {
  219. underlying,
  220. nullptr,
  221. });
  222. },
  223. [&](UsernamePasswordAuthenticationData const& auth_data) -> ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> {
  224. TRY(send_version_identifier_and_method_selection_message(underlying, version, Method::UsernamePassword));
  225. auto auth_response = TRY(send_username_password_authentication_message(underlying, auth_data));
  226. if (auth_response != 0) {
  227. underlying.close();
  228. return Error::from_string_literal("SOCKS authentication failed");
  229. }
  230. auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
  231. if (reply != Reply::Succeeded) {
  232. underlying.close();
  233. return Error::from_string_view(reply_response_name(reply));
  234. }
  235. return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {
  236. underlying,
  237. nullptr,
  238. });
  239. });
  240. }
  241. 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)
  242. {
  243. auto underlying = TRY(server.visit(
  244. [&](u32 ipv4) {
  245. return Core::TCPSocket::connect({ IPv4Address(ipv4), static_cast<u16>(server_port) });
  246. },
  247. [&](ByteString const& hostname) {
  248. return Core::TCPSocket::connect(hostname, static_cast<u16>(server_port));
  249. }));
  250. auto socket = TRY(connect(*underlying, version, target, target_port, auth_data, command));
  251. socket->m_own_underlying_socket = move(underlying);
  252. dbgln("SOCKS proxy connected, have {} available bytes", TRY(socket->m_socket.pending_bytes()));
  253. return socket;
  254. }
  255. }