SOCKSProxy.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #if !BESTHTTP_DISABLE_PROXY
  2. using System;
  3. using System.IO;
  4. using System.Text;
  5. using BestHTTP.Authentication;
  6. using BestHTTP.Extensions;
  7. using BestHTTP.PlatformSupport.Memory;
  8. namespace BestHTTP
  9. {
  10. internal enum SOCKSVersions : byte
  11. {
  12. Unknown = 0x00,
  13. V5 = 0x05
  14. }
  15. /// <summary>
  16. /// https://tools.ietf.org/html/rfc1928
  17. /// The values currently defined for METHOD are:
  18. /// o X'00' NO AUTHENTICATION REQUIRED
  19. /// o X'01' GSSAPI
  20. /// o X'02' USERNAME/PASSWORD
  21. /// o X'03' to X'7F' IANA ASSIGNED
  22. /// o X'80' to X'FE' RESERVED FOR PRIVATE METHODS
  23. /// o X'FF' NO ACCEPTABLE METHODS
  24. /// </summary>
  25. internal enum SOCKSMethods : byte
  26. {
  27. NoAuthenticationRequired = 0x00,
  28. GSSAPI = 0x01,
  29. UsernameAndPassword = 0x02,
  30. NoAcceptableMethods = 0xFF
  31. }
  32. internal enum SOCKSReplies : byte
  33. {
  34. Succeeded = 0x00,
  35. GeneralSOCKSServerFailure = 0x01,
  36. ConnectionNotAllowedByRuleset = 0x02,
  37. NetworkUnreachable = 0x03,
  38. HostUnreachable = 0x04,
  39. ConnectionRefused = 0x05,
  40. TTLExpired = 0x06,
  41. CommandNotSupported = 0x07,
  42. AddressTypeNotSupported = 0x08
  43. }
  44. internal enum SOCKSAddressTypes
  45. {
  46. IPV4 = 0x00,
  47. DomainName = 0x03,
  48. IPv6 = 0x04
  49. }
  50. public sealed class SOCKSProxy : Proxy
  51. {
  52. public SOCKSProxy(Uri address, Credentials credentials)
  53. : base(address, credentials)
  54. { }
  55. internal override string GetRequestPath(Uri uri)
  56. {
  57. return uri.GetRequestPathAndQueryURL();
  58. }
  59. internal override bool SetupRequest(HTTPRequest request)
  60. {
  61. return false;
  62. }
  63. internal override void Connect(Stream stream, HTTPRequest request)
  64. {
  65. var buffer = BufferPool.Get(1024, true);
  66. try
  67. {
  68. int count = 0;
  69. // https://tools.ietf.org/html/rfc1928
  70. // The client connects to the server, and sends a version
  71. // identifier/method selection message:
  72. //
  73. // +----+----------+----------+
  74. // |VER | NMETHODS | METHODS |
  75. // +----+----------+----------+
  76. // | 1 | 1 | 1 to 255 |
  77. // +----+----------+----------+
  78. //
  79. // The VER field is set to X'05' for this version of the protocol. The
  80. // NMETHODS field contains the number of method identifier octets that
  81. // appear in the METHODS field.
  82. //
  83. buffer[count++] = (byte)SOCKSVersions.V5;
  84. if (this.Credentials != null)
  85. {
  86. buffer[count++] = 0x02; // method count
  87. buffer[count++] = (byte)SOCKSMethods.UsernameAndPassword;
  88. buffer[count++] = (byte)SOCKSMethods.NoAuthenticationRequired;
  89. }
  90. else
  91. {
  92. buffer[count++] = 0x01; // method count
  93. buffer[count++] = (byte)SOCKSMethods.NoAuthenticationRequired;
  94. }
  95. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  96. HTTPManager.Logger.Information("SOCKSProxy", string.Format("Sending method negotiation - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count)), request.Context);
  97. // Write negotiation
  98. stream.Write(buffer, 0, count);
  99. // Read result
  100. count = stream.Read(buffer, 0, buffer.Length);
  101. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  102. HTTPManager.Logger.Information("SOCKSProxy", string.Format("Negotiation response - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count)), request.Context);
  103. // The server selects from one of the methods given in METHODS, and
  104. // sends a METHOD selection message:
  105. //
  106. // +----+--------+
  107. // |VER | METHOD |
  108. // +----+--------+
  109. // | 1 | 1 |
  110. // +----+--------+
  111. //
  112. // If the selected METHOD is X'FF', none of the methods listed by the
  113. // client are acceptable, and the client MUST close the connection.
  114. //
  115. // The values currently defined for METHOD are:
  116. //
  117. // o X'00' NO AUTHENTICATION REQUIRED
  118. // o X'01' GSSAPI
  119. // o X'02' USERNAME/PASSWORD
  120. // o X'03' to X'7F' IANA ASSIGNED
  121. // o X'80' to X'FE' RESERVED FOR PRIVATE METHODS
  122. // o X'FF' NO ACCEPTABLE METHODS
  123. //
  124. // The client and server then enter a method-specific sub-negotiation.
  125. SOCKSVersions version = (SOCKSVersions)buffer[0];
  126. SOCKSMethods method = (SOCKSMethods)buffer[1];
  127. // Expected result:
  128. // 1.) Received bytes' count is 2: version + preferred method
  129. // 2.) Version must be 5
  130. // 3.) Preferred method must NOT be 0xFF
  131. if (count != 2)
  132. throw new Exception(string.Format("SOCKS Proxy - Expected read count: 2! count: {0} buffer: {1}" + count.ToString(), BufferToHexStr(buffer, count)));
  133. else if (version != SOCKSVersions.V5)
  134. throw new Exception("SOCKS Proxy - Expected version: 5, received version: " + buffer[0].ToString("X2"));
  135. else if (method == SOCKSMethods.NoAcceptableMethods)
  136. throw new Exception("SOCKS Proxy - Received 'NO ACCEPTABLE METHODS' (0xFF)");
  137. else
  138. {
  139. HTTPManager.Logger.Information("SOCKSProxy", "Method negotiation over. Method: " + method.ToString(), request.Context);
  140. switch (method)
  141. {
  142. case SOCKSMethods.NoAuthenticationRequired:
  143. // nothing to do
  144. break;
  145. case SOCKSMethods.UsernameAndPassword:
  146. if (this.Credentials.UserName.Length > 255)
  147. throw new Exception(string.Format("SOCKS Proxy - Credentials.UserName too long! {0} > 255", this.Credentials.UserName.Length.ToString()));
  148. if (this.Credentials.Password.Length > 255)
  149. throw new Exception(string.Format("SOCKS Proxy - Credentials.Password too long! {0} > 255", this.Credentials.Password.Length.ToString()));
  150. // https://tools.ietf.org/html/rfc1929 : Username/Password Authentication for SOCKS V5
  151. // Once the SOCKS V5 server has started, and the client has selected the
  152. // Username/Password Authentication protocol, the Username/Password
  153. // subnegotiation begins. This begins with the client producing a
  154. // Username/Password request:
  155. //
  156. // +----+------+----------+------+----------+
  157. // |VER | ULEN | UNAME | PLEN | PASSWD |
  158. // +----+------+----------+------+----------+
  159. // | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
  160. // +----+------+----------+------+----------+
  161. HTTPManager.Logger.Information("SOCKSProxy", "starting sub-negotiation", request.Context);
  162. count = 0;
  163. buffer[count++] = 0x01; // version of sub negotiation
  164. WriteString(buffer, ref count, this.Credentials.UserName);
  165. WriteString(buffer, ref count, this.Credentials.Password);
  166. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  167. HTTPManager.Logger.Information("SOCKSProxy", string.Format("Sending username and password sub-negotiation - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count)), request.Context);
  168. // Write negotiation
  169. stream.Write(buffer, 0, count);
  170. // Read result
  171. count = stream.Read(buffer, 0, buffer.Length);
  172. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  173. HTTPManager.Logger.Information("SOCKSProxy", string.Format("Username and password sub-negotiation response - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count)), request.Context);
  174. // The server verifies the supplied UNAME and PASSWD, and sends the
  175. // following response:
  176. //
  177. // +----+--------+
  178. // |VER | STATUS |
  179. // +----+--------+
  180. // | 1 | 1 |
  181. // +----+--------+
  182. // A STATUS field of X'00' indicates success. If the server returns a
  183. // `failure' (STATUS value other than X'00') status, it MUST close the
  184. // connection.
  185. bool success = buffer[1] == 0;
  186. if (count != 2)
  187. throw new Exception(string.Format("SOCKS Proxy - Expected read count: 2! count: {0} buffer: {1}" + count.ToString(), BufferToHexStr(buffer, count)));
  188. else if (!success)
  189. throw new Exception("SOCKS proxy: username+password authentication failed!");
  190. HTTPManager.Logger.Information("SOCKSProxy", "Authenticated!", request.Context);
  191. break;
  192. case SOCKSMethods.GSSAPI:
  193. throw new Exception("SOCKS proxy: GSSAPI not supported!");
  194. case SOCKSMethods.NoAcceptableMethods:
  195. throw new Exception("SOCKS proxy: No acceptable method");
  196. }
  197. }
  198. // The SOCKS request is formed as follows:
  199. //
  200. // +----+-----+-------+------+----------+----------+
  201. // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
  202. // +----+-----+-------+------+----------+----------+
  203. // | 1 | 1 | X'00' | 1 | Variable | 2 |
  204. // +----+-----+-------+------+----------+----------+
  205. //
  206. // Where:
  207. //
  208. // o VER protocol version: X'05'
  209. // o CMD
  210. // o CONNECT X'01'
  211. // o BIND X'02'
  212. // o UDP ASSOCIATE X'03'
  213. // o RSV RESERVED
  214. // o ATYP address type of following address
  215. // o IP V4 address: X'01'
  216. // o DOMAINNAME: X'03'
  217. // o IP V6 address: X'04'
  218. // o DST.ADDR desired destination address
  219. // o DST.PORT desired destination port in network octet
  220. // order
  221. count = 0;
  222. buffer[count++] = (byte)SOCKSVersions.V5; // version: 5
  223. buffer[count++] = 0x01; // command: connect
  224. buffer[count++] = 0x00; // reserved, bust be 0x00
  225. if (request.CurrentUri.IsHostIsAnIPAddress())
  226. {
  227. bool isIPV4 = Extensions.Extensions.IsIpV4AddressValid(request.CurrentUri.Host);
  228. buffer[count++] = isIPV4 ? (byte)SOCKSAddressTypes.IPV4 : (byte)SOCKSAddressTypes.IPv6;
  229. var ipAddress = System.Net.IPAddress.Parse(request.CurrentUri.Host);
  230. var ipBytes = ipAddress.GetAddressBytes();
  231. WriteBytes(buffer, ref count, ipBytes); // destination address
  232. }
  233. else
  234. {
  235. buffer[count++] = (byte)SOCKSAddressTypes.DomainName;
  236. // The first octet of the address field contains the number of octets of name that
  237. // follow, there is no terminating NUL octet.
  238. WriteString(buffer, ref count, request.CurrentUri.Host);
  239. }
  240. // destination port in network octet order
  241. buffer[count++] = (byte)((request.CurrentUri.Port >> 8) & 0xFF);
  242. buffer[count++] = (byte)(request.CurrentUri.Port & 0xFF);
  243. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  244. HTTPManager.Logger.Information("SOCKSProxy", string.Format("Sending connect request - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count)), request.Context);
  245. stream.Write(buffer, 0, count);
  246. count = stream.Read(buffer, 0, buffer.Length);
  247. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  248. HTTPManager.Logger.Information("SOCKSProxy", string.Format("Connect response - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count)), request.Context);
  249. // The SOCKS request information is sent by the client as soon as it has
  250. // established a connection to the SOCKS server, and completed the
  251. // authentication negotiations. The server evaluates the request, and
  252. // returns a reply formed as follows:
  253. //
  254. // +----+-----+-------+------+----------+----------+
  255. // |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
  256. // +----+-----+-------+------+----------+----------+
  257. // | 1 | 1 | X'00' | 1 | Variable | 2 |
  258. // +----+-----+-------+------+----------+----------+
  259. //
  260. // Where:
  261. // o VER protocol version: X'05'
  262. // o REP Reply field:
  263. // o X'00' succeeded
  264. // o X'01' general SOCKS server failure
  265. // o X'02' connection not allowed by ruleset
  266. // o X'03' Network unreachable
  267. // o X'04' Host unreachable
  268. // o X'05' Connection refused
  269. // o X'06' TTL expired
  270. // o X'07' Command not supported
  271. // o X'08' Address type not supported
  272. // o X'09' to X'FF' unassigned
  273. // o RSV RESERVED
  274. // o ATYP address type of following address
  275. // o IP V4 address: X'01'
  276. // o DOMAINNAME: X'03'
  277. // o IP V6 address: X'04'
  278. // o BND.ADDR server bound address
  279. // o BND.PORT server bound port in network octet order
  280. //
  281. // Fields marked RESERVED (RSV) must be set to X'00'.
  282. version = (SOCKSVersions)buffer[0];
  283. SOCKSReplies reply = (SOCKSReplies)buffer[1];
  284. // at least 10 bytes expected as a result
  285. if (count < 10)
  286. throw new Exception(string.Format("SOCKS proxy: not enough data returned by the server. Expected count is at least 10 bytes, server returned {0} bytes! content: {1}", count.ToString(), BufferToHexStr(buffer, count)));
  287. else if (reply != SOCKSReplies.Succeeded)
  288. throw new Exception("SOCKS proxy error: " + reply.ToString());
  289. HTTPManager.Logger.Information("SOCKSProxy", "Connected!", request.Context);
  290. }
  291. finally
  292. {
  293. BufferPool.Release(buffer);
  294. }
  295. }
  296. private void WriteString(byte[] buffer, ref int count, string str)
  297. {
  298. // Get the bytes
  299. int byteCount = Encoding.UTF8.GetByteCount(str);
  300. if (byteCount > 255)
  301. throw new Exception(string.Format("SOCKS Proxy - String is too large ({0}) to fit in 255 bytes!", byteCount.ToString()));
  302. // number of bytes
  303. buffer[count++] = (byte)byteCount;
  304. // and the bytes itself
  305. Encoding.UTF8.GetBytes(str, 0, str.Length, buffer, count);
  306. count += byteCount;
  307. }
  308. private void WriteBytes(byte[] buffer, ref int count, byte[] bytes)
  309. {
  310. Array.Copy(bytes, 0, buffer, count, bytes.Length);
  311. count += bytes.Length;
  312. }
  313. private string BufferToHexStr(byte[] buffer, int count)
  314. {
  315. StringBuilder sb = new StringBuilder(count * 2);
  316. for (int i = 0; i < count; ++i)
  317. sb.AppendFormat("0x{0} ", buffer[i].ToString("X2"));
  318. return sb.ToString();
  319. }
  320. }
  321. }
  322. #endif