SOCKSProxy.cs 16 KB

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