PageRenderTime 90ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/MSNPSHARP_DEV/ProxyServer/Socks5Handler.cs

http://msnp-sharp.googlecode.com/
C# | 277 lines | 201 code | 4 blank | 72 comment | 30 complexity | b05c3f8ab0a85b147cad77acdbfe0f3f MD5 | raw file
  1. /*
  2. Copyright ?2002, The KPD-Team
  3. All rights reserved.
  4. http://www.mentalis.org/
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions
  7. are met:
  8. - Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. - Neither the name of the KPD-Team, nor the names of its contributors
  11. may be used to endorse or promote products derived from this
  12. software without specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  14. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  15. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  16. FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
  17. THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  18. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  20. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  21. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  22. STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  24. OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. using System;
  27. using System.Net;
  28. using System.Net.Sockets;
  29. using System.Text;
  30. using Org.Mentalis.Proxy;
  31. using Org.Mentalis.Proxy.Socks.Authentication;
  32. namespace Org.Mentalis.Proxy.Socks {
  33. ///<summary>Implements the SOCKS5 protocol.</summary>
  34. internal sealed class Socks5Handler : SocksHandler {
  35. ///<summary>Initializes a new instance of the Socks5Handler class.</summary>
  36. ///<param name="ClientConnection">The connection with the client.</param>
  37. ///<param name="Callback">The method to call when the SOCKS negotiation is complete.</param>
  38. ///<param name="AuthList">The authentication list to use when clients connect.</param>
  39. ///<exception cref="ArgumentNullException"><c>Callback</c> is null.</exception>
  40. ///<remarks>If the AuthList parameter is null, no authentication will be required when a client connects to the proxy server.</remarks>
  41. public Socks5Handler(Socket ClientConnection, NegotiationCompleteDelegate Callback, AuthenticationList AuthList) : base(ClientConnection, Callback) {
  42. this.AuthList = AuthList;
  43. }
  44. ///<summary>Initializes a new instance of the Socks5Handler class.</summary>
  45. ///<param name="ClientConnection">The connection with the client.</param>
  46. ///<param name="Callback">The method to call when the SOCKS negotiation is complete.</param>
  47. ///<exception cref="ArgumentNullException"><c>Callback</c> is null.</exception>
  48. public Socks5Handler(Socket ClientConnection, NegotiationCompleteDelegate Callback) : this(ClientConnection, Callback, null) {}
  49. ///<summary>Checks whether a specific request is a valid SOCKS request or not.</summary>
  50. ///<param name="Request">The request array to check.</param>
  51. ///<returns>True is the specified request is valid, false otherwise</returns>
  52. protected override bool IsValidRequest(byte [] Request) {
  53. try {
  54. return (Request.Length == Request[0] + 1);
  55. } catch {
  56. return false;
  57. }
  58. }
  59. ///<summary>Processes a SOCKS request from a client and selects an authentication method.</summary>
  60. ///<param name="Request">The request to process.</param>
  61. protected override void ProcessRequest(byte [] Request) {
  62. try {
  63. byte Ret = 255;
  64. for (int Cnt = 1; Cnt < Request.Length; Cnt++) {
  65. if (Request[Cnt] == 0 && AuthList == null) { //0 = No authentication
  66. Ret = 0;
  67. AuthMethod = new AuthNone();
  68. break;
  69. } else if (Request[Cnt] == 2 && AuthList != null) { //2 = user/pass
  70. Ret = 2;
  71. AuthMethod = new AuthUserPass(AuthList);
  72. if (AuthList != null)
  73. break;
  74. }
  75. }
  76. Connection.BeginSend(new byte[]{5, Ret}, 0, 2, SocketFlags.None, new AsyncCallback(this.OnAuthSent), Connection);
  77. } catch {
  78. Dispose(false);
  79. }
  80. }
  81. ///<summary>Called when client has been notified of the selected authentication method.</summary>
  82. ///<param name="ar">The result of the asynchronous operation.</param>
  83. private void OnAuthSent(IAsyncResult ar) {
  84. try {
  85. if (Connection.EndSend(ar) <= 0 || AuthMethod == null) {
  86. Dispose(false);
  87. return;
  88. }
  89. AuthMethod.StartAuthentication(Connection, new AuthenticationCompleteDelegate(this.OnAuthenticationComplete));
  90. } catch {
  91. Dispose(false);
  92. }
  93. }
  94. ///<summary>Called when the authentication is complete.</summary>
  95. ///<param name="Success">Indicates whether the authentication was successful ot not.</param>
  96. private void OnAuthenticationComplete(bool Success) {
  97. try {
  98. if (Success) {
  99. Bytes = null;
  100. Connection.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnRecvRequest), Connection);
  101. } else {
  102. Dispose(false);
  103. }
  104. } catch {
  105. Dispose(false);
  106. }
  107. }
  108. ///<summary>Called when we received the request of the client.</summary>
  109. ///<param name="ar">The result of the asynchronous operation.</param>
  110. private void OnRecvRequest(IAsyncResult ar) {
  111. try {
  112. int Ret = Connection.EndReceive(ar);
  113. if (Ret <= 0) {
  114. Dispose(false);
  115. return;
  116. }
  117. AddBytes(Buffer, Ret);
  118. if (IsValidQuery(Bytes))
  119. ProcessQuery(Bytes);
  120. else
  121. Connection.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnRecvRequest), Connection);
  122. } catch {
  123. Dispose(false);
  124. }
  125. }
  126. ///<summary>Checks whether a specified query is a valid query or not.</summary>
  127. ///<param name="Query">The query to check.</param>
  128. ///<returns>True if the query is valid, false otherwise.</returns>
  129. private bool IsValidQuery(byte [] Query) {
  130. try {
  131. switch(Query[3]) {
  132. case 1: //IPv4 address
  133. return (Query.Length == 10);
  134. case 3: //Domain name
  135. return (Query.Length == Query[4] + 7);
  136. case 4: //IPv6 address
  137. //Not supported
  138. Dispose(8);
  139. return false;
  140. default:
  141. Dispose(false);
  142. return false;
  143. }
  144. } catch {
  145. return false;
  146. }
  147. }
  148. ///<summary>Processes a received query.</summary>
  149. ///<param name="Query">The query to process.</param>
  150. private void ProcessQuery(byte [] Query) {
  151. try {
  152. switch(Query[1]) {
  153. case 1: //CONNECT
  154. IPAddress RemoteIP = null;
  155. int RemotePort = 0;
  156. if (Query[3] == 1) {
  157. RemoteIP = IPAddress.Parse(Query[4].ToString() + "." + Query[5].ToString() + "." + Query[6].ToString() + "." + Query[7].ToString());
  158. RemotePort = Query[8] * 256 + Query[9];
  159. } else if( Query[3] == 3) {
  160. RemoteIP = Dns.GetHostEntry(Encoding.ASCII.GetString(Query, 5, Query[4])).AddressList[0];
  161. RemotePort = Query[4] + 5;
  162. RemotePort = Query[RemotePort] * 256 + Query[RemotePort + 1];
  163. }
  164. RemoteConnection = new Socket(RemoteIP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  165. RemoteConnection.BeginConnect(new IPEndPoint(RemoteIP, RemotePort), new AsyncCallback(this.OnConnected), RemoteConnection);
  166. break;
  167. case 2: //BIND
  168. byte[] Reply = new byte[10];
  169. byte[] LocalIP = Listener.GetLocalExternalIP().GetAddressBytes();
  170. AcceptSocket = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  171. AcceptSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
  172. AcceptSocket.Listen(50);
  173. Reply[0] = 5; //Version 5
  174. Reply[1] = 0; //Everything is ok :)
  175. Reply[2] = 0; //Reserved
  176. Reply[3] = 1; //We're going to send a IPv4 address
  177. Reply[4] = LocalIP[0];// (byte)(Math.Floor((double)(LocalIP % 256))); //IP Address/1
  178. Reply[5] = LocalIP[1];//(byte)(Math.Floor((double)(LocalIP % 65536) / 256)); //IP Address/2
  179. Reply[6] = LocalIP[2];//(byte)(Math.Floor((double)(LocalIP % 16777216) / 65536)); //IP Address/3
  180. Reply[7] = LocalIP[3];//(byte)(Math.Floor((double)(LocalIP / 16777216))); //IP Address/4
  181. Reply[8] = (byte)(Math.Floor((double)((IPEndPoint)AcceptSocket.LocalEndPoint).Port / 256)); //Port/1
  182. Reply[9] = (byte)(((IPEndPoint)AcceptSocket.LocalEndPoint).Port % 256); //Port/2
  183. Connection.BeginSend(Reply, 0, Reply.Length, SocketFlags.None, new AsyncCallback(this.OnStartAccept), Connection);
  184. break;
  185. case 3: //ASSOCIATE
  186. //ASSOCIATE is not implemented (yet?)
  187. Dispose(7);
  188. break;
  189. default:
  190. Dispose(7);
  191. break;
  192. }
  193. } catch {
  194. Dispose(1);
  195. }
  196. }
  197. ///<summary>Called when we're successfully connected to the remote host.</summary>
  198. ///<param name="ar">The result of the asynchronous operation.</param>
  199. private void OnConnected(IAsyncResult ar) {
  200. try {
  201. RemoteConnection.EndConnect(ar);
  202. Dispose(0);
  203. } catch {
  204. Dispose(1);
  205. }
  206. }
  207. ///<summary>Called when there's an incoming connection in the AcceptSocket queue.</summary>
  208. ///<param name="ar">The result of the asynchronous operation.</param>
  209. protected override void OnAccept(IAsyncResult ar) {
  210. try {
  211. RemoteConnection = AcceptSocket.EndAccept(ar);
  212. AcceptSocket.Close();
  213. AcceptSocket = null;
  214. Dispose(0);
  215. } catch {
  216. Dispose(1);
  217. }
  218. }
  219. ///<summary>Sends a reply to the client connection and disposes it afterwards.</summary>
  220. ///<param name="Value">A byte that contains the reply code to send to the client.</param>
  221. protected override void Dispose(byte Value) {
  222. byte [] ToSend;
  223. try {
  224. ToSend = new byte[]{5, Value, 0, 1,
  225. ((IPEndPoint)RemoteConnection.LocalEndPoint).Address.GetAddressBytes()[0],
  226. ((IPEndPoint)RemoteConnection.LocalEndPoint).Address.GetAddressBytes()[1],
  227. ((IPEndPoint)RemoteConnection.LocalEndPoint).Address.GetAddressBytes()[2],
  228. ((IPEndPoint)RemoteConnection.LocalEndPoint).Address.GetAddressBytes()[3],
  229. (byte)(Math.Floor((double)((IPEndPoint)RemoteConnection.LocalEndPoint).Port / 256)),
  230. (byte)(((IPEndPoint)RemoteConnection.LocalEndPoint).Port % 256)};
  231. } catch {
  232. ToSend = new byte[] {5, 1, 0, 1, 0, 0, 0, 0, 0, 0};
  233. }
  234. try {
  235. Connection.BeginSend(ToSend, 0, ToSend.Length, SocketFlags.None, (AsyncCallback)(ToSend[1] == 0 ? new AsyncCallback(this.OnDisposeGood) : new AsyncCallback(this.OnDisposeBad)), Connection);
  236. } catch {
  237. Dispose(false);
  238. }
  239. }
  240. ///<summary>Gets or sets the the AuthBase object to use when trying to authenticate the SOCKS client.</summary>
  241. ///<value>The AuthBase object to use when trying to authenticate the SOCKS client.</value>
  242. ///<exception cref="ArgumentNullException">The specified value is null.</exception>
  243. private AuthBase AuthMethod {
  244. get {
  245. return m_AuthMethod;
  246. }
  247. set {
  248. if (value == null)
  249. throw new ArgumentNullException();
  250. m_AuthMethod = value;
  251. }
  252. }
  253. ///<summary>Gets or sets the AuthenticationList object to use when trying to authenticate the SOCKS client.</summary>
  254. ///<value>The AuthenticationList object to use when trying to authenticate the SOCKS client.</value>
  255. private AuthenticationList AuthList {
  256. get {
  257. return m_AuthList;
  258. }
  259. set {
  260. m_AuthList = value;
  261. }
  262. }
  263. // private variables
  264. /// <summary>Holds the value of the AuthList property.</summary>
  265. private AuthenticationList m_AuthList;
  266. /// <summary>Holds the value of the AuthMethod property.</summary>
  267. private AuthBase m_AuthMethod;
  268. }
  269. }