SOCKSProxyClient.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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";
  66. case Reply::GeneralSocksServerFailure:
  67. return "GeneralSocksServerFailure";
  68. case Reply::ConnectionNotAllowedByRuleset:
  69. return "ConnectionNotAllowedByRuleset";
  70. case Reply::NetworkUnreachable:
  71. return "NetworkUnreachable";
  72. case Reply::HostUnreachable:
  73. return "HostUnreachable";
  74. case Reply::ConnectionRefused:
  75. return "ConnectionRefused";
  76. case Reply::TTLExpired:
  77. return "TTLExpired";
  78. case Reply::CommandNotSupported:
  79. return "CommandNotSupported";
  80. case Reply::AddressTypeNotSupported:
  81. return "AddressTypeNotSupported";
  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. DuplexMemoryStream 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 = 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. [&](String 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 = 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. 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 = 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 = 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 = stream.copy_into_contiguous_buffer();
  144. size = TRY(socket.write({ buffer.data(), buffer.size() }));
  145. if (size != buffer.size())
  146. return Error::from_string_literal("SOCKS negotiation failed: Failed to send connect request");
  147. Socks5ConnectResponseHeader response_header;
  148. size = TRY(socket.read({ &response_header, sizeof(response_header) })).size();
  149. if (size != sizeof(response_header))
  150. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response header");
  151. if (response_header.version_identifier != to_underlying(version))
  152. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  153. u8 response_address_type;
  154. size = TRY(socket.read({ &response_address_type, sizeof(response_address_type) })).size();
  155. if (size != sizeof(response_address_type))
  156. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address type");
  157. switch (AddressType(response_address_type)) {
  158. case AddressType::IPV4: {
  159. u8 response_address_data[4];
  160. size = TRY(socket.read({ response_address_data, sizeof(response_address_data) })).size();
  161. if (size != sizeof(response_address_data))
  162. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address data");
  163. break;
  164. }
  165. case AddressType::DomainName: {
  166. u8 response_address_length;
  167. size = TRY(socket.read({ &response_address_length, sizeof(response_address_length) })).size();
  168. if (size != sizeof(response_address_length))
  169. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address length");
  170. ByteBuffer buffer;
  171. buffer.resize(response_address_length);
  172. size = TRY(socket.read(buffer)).size();
  173. if (size != response_address_length)
  174. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response address data");
  175. break;
  176. }
  177. case AddressType::IPV6:
  178. default:
  179. return Error::from_string_literal("SOCKS negotiation failed: Invalid connect response address type");
  180. }
  181. u16 bound_port;
  182. size = TRY(socket.read({ &bound_port, sizeof(bound_port) })).size();
  183. if (size != sizeof(bound_port))
  184. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive connect response bound port");
  185. return Reply(response_header.status);
  186. }
  187. ErrorOr<u8> send_username_password_authentication_message(Core::Stream::Socket& socket, Core::SOCKSProxyClient::UsernamePasswordAuthenticationData const& auth_data)
  188. {
  189. DuplexMemoryStream stream;
  190. u8 version = 0x01;
  191. auto size = stream.write({ &version, sizeof(version) });
  192. if (size != sizeof(version))
  193. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  194. u8 username_length = auth_data.username.length();
  195. size = stream.write({ &username_length, sizeof(username_length) });
  196. if (size != sizeof(username_length))
  197. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  198. size = stream.write({ auth_data.username.characters(), auth_data.username.length() });
  199. if (size != auth_data.username.length())
  200. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  201. u8 password_length = auth_data.password.length();
  202. size = stream.write({ &password_length, sizeof(password_length) });
  203. if (size != sizeof(password_length))
  204. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  205. size = stream.write({ auth_data.password.characters(), auth_data.password.length() });
  206. if (size != auth_data.password.length())
  207. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  208. auto buffer = stream.copy_into_contiguous_buffer();
  209. size = TRY(socket.write(buffer));
  210. if (size != buffer.size())
  211. return Error::from_string_literal("SOCKS negotiation failed: Failed to send username/password authentication message");
  212. Socks5UsernamePasswordResponse response;
  213. size = TRY(socket.read({ &response, sizeof(response) })).size();
  214. if (size != sizeof(response))
  215. return Error::from_string_literal("SOCKS negotiation failed: Failed to receive username/password authentication response");
  216. if (response.version_identifier != version)
  217. return Error::from_string_literal("SOCKS negotiation failed: Invalid version identifier");
  218. return response.status;
  219. }
  220. }
  221. namespace Core {
  222. SOCKSProxyClient::~SOCKSProxyClient()
  223. {
  224. close();
  225. m_socket.on_ready_to_read = nullptr;
  226. }
  227. ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> SOCKSProxyClient::connect(Socket& underlying, Version version, HostOrIPV4 const& target, int target_port, Variant<UsernamePasswordAuthenticationData, Empty> const& auth_data, Command command)
  228. {
  229. if (version != Version::V5)
  230. return Error::from_string_literal("SOCKS version not supported");
  231. return auth_data.visit(
  232. [&](Empty) -> ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> {
  233. TRY(send_version_identifier_and_method_selection_message(underlying, version, Method::NoAuth));
  234. auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
  235. if (reply != Reply::Succeeded) {
  236. underlying.close();
  237. return Error::from_string_literal(reply_response_name(reply));
  238. }
  239. return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {
  240. underlying,
  241. nullptr,
  242. });
  243. },
  244. [&](UsernamePasswordAuthenticationData const& auth_data) -> ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> {
  245. TRY(send_version_identifier_and_method_selection_message(underlying, version, Method::UsernamePassword));
  246. auto auth_response = TRY(send_username_password_authentication_message(underlying, auth_data));
  247. if (auth_response != 0) {
  248. underlying.close();
  249. return Error::from_string_literal("SOCKS authentication failed");
  250. }
  251. auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
  252. if (reply != Reply::Succeeded) {
  253. underlying.close();
  254. return Error::from_string_literal(reply_response_name(reply));
  255. }
  256. return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {
  257. underlying,
  258. nullptr,
  259. });
  260. });
  261. }
  262. 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)
  263. {
  264. auto underlying = TRY(server.visit(
  265. [&](u32 ipv4) {
  266. return Core::Stream::TCPSocket::connect({ IPv4Address(ipv4), static_cast<u16>(server_port) });
  267. },
  268. [&](String const& hostname) {
  269. return Core::Stream::TCPSocket::connect(hostname, static_cast<u16>(server_port));
  270. }));
  271. auto socket = TRY(connect(*underlying, version, target, target_port, auth_data, command));
  272. socket->m_own_underlying_socket = move(underlying);
  273. dbgln("SOCKS proxy connected, have {} available bytes", TRY(socket->m_socket.pending_bytes()));
  274. return socket;
  275. }
  276. }