SMB1Client.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /* Copyright (C) 2014-2017 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Threading;
  13. using SMBLibrary.NetBios;
  14. using SMBLibrary.SMB1;
  15. using Utilities;
  16. namespace SMBLibrary.Client
  17. {
  18. public class SMB1Client
  19. {
  20. public const int NetBiosOverTCPPort = 139;
  21. public const int DirectTCPPort = 445;
  22. public const string NTLanManagerDialect = "NT LM 0.12";
  23. private SMBTransportType m_transport;
  24. private bool m_isConnected;
  25. private Socket m_clientSocket;
  26. private IAsyncResult m_currentAsyncResult;
  27. private object m_incomingQueueLock = new object();
  28. private List<SMB1Message> m_incomingQueue = new List<SMB1Message>();
  29. private EventWaitHandle m_incomingQueueEventHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
  30. public SMB1Client()
  31. {
  32. }
  33. public bool Connect(IPAddress serverAddress, SMBTransportType transport)
  34. {
  35. m_transport = transport;
  36. if (!m_isConnected)
  37. {
  38. m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  39. int port;
  40. if (transport == SMBTransportType.DirectTCPTransport)
  41. {
  42. port = DirectTCPPort;
  43. }
  44. else
  45. {
  46. port = NetBiosOverTCPPort;
  47. }
  48. try
  49. {
  50. m_clientSocket.Connect(serverAddress, port);
  51. }
  52. catch (SocketException)
  53. {
  54. return false;
  55. }
  56. ConnectionState state = new ConnectionState();
  57. NBTConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  58. m_currentAsyncResult = m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnServerSocketReceive), state);
  59. bool supportsCIFS = NegotiateNTLanManagerDialect();
  60. if (!supportsCIFS)
  61. {
  62. m_clientSocket.Close();
  63. }
  64. else
  65. {
  66. m_isConnected = true;
  67. }
  68. }
  69. return m_isConnected;
  70. }
  71. public void Disconnect()
  72. {
  73. if (m_isConnected)
  74. {
  75. m_clientSocket.Disconnect(false);
  76. m_isConnected = false;
  77. }
  78. }
  79. private bool NegotiateNTLanManagerDialect()
  80. {
  81. if (m_transport == SMBTransportType.NetBiosOverTCP)
  82. {
  83. SessionRequestPacket sessionRequest = new SessionRequestPacket();
  84. sessionRequest.CalledName = NetBiosUtils.GetMSNetBiosName("*SMBSERVER", NetBiosSuffix.FileServiceService); ;
  85. sessionRequest.CallingName = NetBiosUtils.GetMSNetBiosName(Environment.MachineName, NetBiosSuffix.WorkstationService);
  86. TrySendPacket(m_clientSocket, sessionRequest);
  87. }
  88. NegotiateRequest request = new NegotiateRequest();
  89. request.Dialects.Add(NTLanManagerDialect);
  90. TrySendMessage(m_clientSocket, request);
  91. SMB1Message reply = WaitForMessage(CommandName.SMB_COM_NEGOTIATE);
  92. if (reply == null)
  93. {
  94. return false;
  95. }
  96. if (reply.Commands[0] is NegotiateResponse)
  97. {
  98. NegotiateResponse response = (NegotiateResponse)reply.Commands[0];
  99. return true;
  100. }
  101. else if (reply.Commands[0] is NegotiateResponseExtended)
  102. {
  103. NegotiateResponseExtended response = (NegotiateResponseExtended)reply.Commands[0];
  104. return true;
  105. }
  106. else
  107. {
  108. return false;
  109. }
  110. }
  111. private void OnServerSocketReceive(IAsyncResult ar)
  112. {
  113. if (ar != m_currentAsyncResult)
  114. {
  115. // We ignore calls for old sockets which we no longer use
  116. // See: http://rajputyh.blogspot.co.il/2010/04/solve-exception-message-iasyncresult.html
  117. return;
  118. }
  119. ConnectionState state = (ConnectionState)ar.AsyncState;
  120. if (!m_clientSocket.Connected)
  121. {
  122. return;
  123. }
  124. int numberOfBytesReceived = 0;
  125. try
  126. {
  127. numberOfBytesReceived = m_clientSocket.EndReceive(ar);
  128. }
  129. catch (ObjectDisposedException)
  130. {
  131. Log("[ReceiveCallback] EndReceive ObjectDisposedException");
  132. return;
  133. }
  134. catch (SocketException ex)
  135. {
  136. Log("[ReceiveCallback] EndReceive SocketException: " + ex.Message);
  137. return;
  138. }
  139. if (numberOfBytesReceived == 0)
  140. {
  141. m_isConnected = false;
  142. }
  143. else
  144. {
  145. NBTConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  146. buffer.SetNumberOfBytesReceived(numberOfBytesReceived);
  147. ProcessConnectionBuffer(state);
  148. try
  149. {
  150. m_currentAsyncResult = m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnServerSocketReceive), state);
  151. }
  152. catch (ObjectDisposedException)
  153. {
  154. m_isConnected = false;
  155. Log("[ReceiveCallback] BeginReceive ObjectDisposedException");
  156. }
  157. catch (SocketException ex)
  158. {
  159. m_isConnected = false;
  160. Log("[ReceiveCallback] BeginReceive SocketException: " + ex.Message);
  161. }
  162. }
  163. }
  164. private void ProcessConnectionBuffer(ConnectionState state)
  165. {
  166. NBTConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;
  167. while (receiveBuffer.HasCompletePacket())
  168. {
  169. SessionPacket packet = null;
  170. try
  171. {
  172. packet = receiveBuffer.DequeuePacket();
  173. }
  174. catch (Exception)
  175. {
  176. m_clientSocket.Close();
  177. break;
  178. }
  179. if (packet != null)
  180. {
  181. ProcessPacket(packet, state);
  182. }
  183. }
  184. }
  185. private void ProcessPacket(SessionPacket packet, ConnectionState state)
  186. {
  187. if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  188. {
  189. // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
  190. }
  191. else if (packet is PositiveSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  192. {
  193. }
  194. else if (packet is NegativeSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  195. {
  196. m_clientSocket.Close();
  197. m_isConnected = false;
  198. }
  199. else if (packet is SessionMessagePacket)
  200. {
  201. SMB1Message message;
  202. try
  203. {
  204. message = SMB1Message.GetSMB1Message(packet.Trailer);
  205. }
  206. catch (Exception ex)
  207. {
  208. Log("Invalid SMB1 message: " + ex.Message);
  209. m_clientSocket.Close();
  210. m_isConnected = false;
  211. return;
  212. }
  213. lock (m_incomingQueueLock)
  214. {
  215. m_incomingQueue.Add(message);
  216. m_incomingQueueEventHandle.Set();
  217. }
  218. }
  219. }
  220. public SMB1Message WaitForMessage(CommandName commandName)
  221. {
  222. const int TimeOut = 5000;
  223. Stopwatch stopwatch = new Stopwatch();
  224. stopwatch.Start();
  225. while (stopwatch.ElapsedMilliseconds < TimeOut)
  226. {
  227. lock (m_incomingQueueLock)
  228. {
  229. for (int index = 0; index < m_incomingQueue.Count; index++)
  230. {
  231. SMB1Message message = m_incomingQueue[index];
  232. if (message.Commands[0].CommandName == commandName)
  233. {
  234. m_incomingQueue.RemoveAt(index);
  235. return message;
  236. }
  237. }
  238. }
  239. m_incomingQueueEventHandle.WaitOne(100);
  240. }
  241. return null;
  242. }
  243. public void Log(string message)
  244. {
  245. System.Diagnostics.Debug.Print(message);
  246. }
  247. public static void TrySendMessage(Socket serverSocket, SMB1Command request)
  248. {
  249. SMB1Message message = new SMB1Message();
  250. message.Commands.Add(request);
  251. TrySendMessage(serverSocket, message);
  252. }
  253. public static void TrySendMessage(Socket serverSocket, SMB1Message message)
  254. {
  255. SessionMessagePacket packet = new SessionMessagePacket();
  256. packet.Trailer = message.GetBytes();
  257. TrySendPacket(serverSocket, packet);
  258. }
  259. public static void TrySendPacket(Socket serverSocket, SessionPacket response)
  260. {
  261. try
  262. {
  263. serverSocket.Send(response.GetBytes());
  264. }
  265. catch (SocketException)
  266. {
  267. }
  268. catch (ObjectDisposedException)
  269. {
  270. }
  271. }
  272. }
  273. }