SMB2Client.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /* Copyright (C) 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.Authentication.NTLM;
  14. using SMBLibrary.NetBios;
  15. using SMBLibrary.Services;
  16. using SMBLibrary.SMB2;
  17. using Utilities;
  18. namespace SMBLibrary.Client
  19. {
  20. public class SMB2Client : ISMBClient
  21. {
  22. public const int NetBiosOverTCPPort = 139;
  23. public const int DirectTCPPort = 445;
  24. private SMBTransportType m_transport;
  25. private bool m_isConnected;
  26. private bool m_isLoggedIn;
  27. private Socket m_clientSocket;
  28. private IAsyncResult m_currentAsyncResult;
  29. private object m_incomingQueueLock = new object();
  30. private List<SMB2Command> m_incomingQueue = new List<SMB2Command>();
  31. private EventWaitHandle m_incomingQueueEventHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
  32. private uint m_messageID = 0;
  33. private SMB2Dialect m_dialect;
  34. private uint m_maxTransactSize;
  35. private uint m_maxReadSize;
  36. private uint m_maxWriteSize;
  37. private ulong m_sessionID;
  38. private byte[] m_securityBlob;
  39. private byte[] m_sessionKey;
  40. public SMB2Client()
  41. {
  42. }
  43. public bool Connect(IPAddress serverAddress, SMBTransportType transport)
  44. {
  45. m_transport = transport;
  46. if (!m_isConnected)
  47. {
  48. m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  49. int port;
  50. if (transport == SMBTransportType.DirectTCPTransport)
  51. {
  52. port = DirectTCPPort;
  53. }
  54. else
  55. {
  56. port = NetBiosOverTCPPort;
  57. }
  58. try
  59. {
  60. m_clientSocket.Connect(serverAddress, port);
  61. }
  62. catch (SocketException)
  63. {
  64. return false;
  65. }
  66. ConnectionState state = new ConnectionState();
  67. NBTConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  68. m_currentAsyncResult = m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnClientSocketReceive), state);
  69. bool supportsDialect = NegotiateDialect();
  70. if (!supportsDialect)
  71. {
  72. m_clientSocket.Close();
  73. }
  74. else
  75. {
  76. m_isConnected = true;
  77. }
  78. }
  79. return m_isConnected;
  80. }
  81. public void Disconnect()
  82. {
  83. if (m_isConnected)
  84. {
  85. m_clientSocket.Disconnect(false);
  86. m_isConnected = false;
  87. }
  88. }
  89. private bool NegotiateDialect()
  90. {
  91. NegotiateRequest request = new NegotiateRequest();
  92. request.SecurityMode = SecurityMode.SigningEnabled;
  93. request.ClientGuid = Guid.NewGuid();
  94. request.ClientStartTime = DateTime.Now;
  95. request.Dialects.Add(SMB2Dialect.SMB202);
  96. request.Dialects.Add(SMB2Dialect.SMB210);
  97. TrySendCommand(request);
  98. NegotiateResponse response = WaitForCommand(SMB2CommandName.Negotiate) as NegotiateResponse;
  99. if (response != null && response.Header.Status == NTStatus.STATUS_SUCCESS)
  100. {
  101. m_dialect = response.DialectRevision;
  102. m_maxTransactSize = response.MaxTransactSize;
  103. m_maxReadSize = response.MaxReadSize;
  104. m_maxWriteSize = response.MaxWriteSize;
  105. m_securityBlob = response.SecurityBuffer;
  106. return true;
  107. }
  108. return false;
  109. }
  110. public NTStatus Login(string domainName, string userName, string password)
  111. {
  112. return Login(domainName, userName, password, AuthenticationMethod.NTLMv2);
  113. }
  114. public NTStatus Login(string domainName, string userName, string password, AuthenticationMethod authenticationMethod)
  115. {
  116. if (!m_isConnected)
  117. {
  118. throw new InvalidOperationException("A connection must be successfully established before attempting login");
  119. }
  120. SessionSetupRequest request = new SessionSetupRequest();
  121. request.SecurityMode = SecurityMode.SigningEnabled;
  122. request.SecurityBuffer = NTLMAuthenticationHelper.GetNegotiateMessage(m_securityBlob, domainName, authenticationMethod);
  123. TrySendCommand(request);
  124. SMB2Command response = WaitForCommand(SMB2CommandName.SessionSetup);
  125. if (response != null)
  126. {
  127. if (response.Header.Status == NTStatus.STATUS_MORE_PROCESSING_REQUIRED && response is SessionSetupResponse)
  128. {
  129. m_sessionID = response.Header.SessionID;
  130. request = new SessionSetupRequest();
  131. request.SecurityMode = SecurityMode.SigningEnabled;
  132. request.SecurityBuffer = NTLMAuthenticationHelper.GetAuthenticateMessage(((SessionSetupResponse)response).SecurityBuffer, domainName, userName, password, authenticationMethod, out m_sessionKey);
  133. TrySendCommand(request);
  134. response = WaitForCommand(SMB2CommandName.SessionSetup);
  135. if (response != null)
  136. {
  137. m_isLoggedIn = (response.Header.Status == NTStatus.STATUS_SUCCESS);
  138. return response.Header.Status;
  139. }
  140. }
  141. else
  142. {
  143. return response.Header.Status;
  144. }
  145. }
  146. return NTStatus.STATUS_INVALID_SMB;
  147. }
  148. public NTStatus Logoff()
  149. {
  150. if (!m_isConnected)
  151. {
  152. throw new InvalidOperationException("A login session must be successfully established before attempting logoff");
  153. }
  154. LogoffRequest request = new LogoffRequest();
  155. TrySendCommand(request);
  156. SMB2Command response = WaitForCommand(SMB2CommandName.Logoff);
  157. if (response != null)
  158. {
  159. m_isLoggedIn = (response.Header.Status != NTStatus.STATUS_SUCCESS);
  160. return response.Header.Status;
  161. }
  162. return NTStatus.STATUS_INVALID_SMB;
  163. }
  164. public List<string> ListShares(out NTStatus status)
  165. {
  166. if (!m_isConnected || !m_isLoggedIn)
  167. {
  168. throw new InvalidOperationException("A login session must be successfully established before retrieving share list");
  169. }
  170. ISMBFileStore namedPipeShare = TreeConnect("IPC$", out status);
  171. if (namedPipeShare == null)
  172. {
  173. return null;
  174. }
  175. List<string> shares = ServerServiceHelper.ListShares(namedPipeShare, SMBLibrary.Services.ShareType.DiskDrive, out status);
  176. namedPipeShare.Disconnect();
  177. return shares;
  178. }
  179. public ISMBFileStore TreeConnect(string shareName, out NTStatus status)
  180. {
  181. if (!m_isConnected || !m_isLoggedIn)
  182. {
  183. throw new InvalidOperationException("A login session must be successfully established before connecting to a share");
  184. }
  185. IPAddress serverIPAddress = ((IPEndPoint)m_clientSocket.RemoteEndPoint).Address;
  186. string sharePath = String.Format(@"\\{0}\{1}", serverIPAddress.ToString(), shareName);
  187. TreeConnectRequest request = new TreeConnectRequest();
  188. request.Path = sharePath;
  189. TrySendCommand(request);
  190. SMB2Command response = WaitForCommand(SMB2CommandName.TreeConnect);
  191. if (response != null)
  192. {
  193. status = response.Header.Status;
  194. if (response.Header.Status == NTStatus.STATUS_SUCCESS && response is TreeConnectResponse)
  195. {
  196. return new SMB2FileStore(this, response.Header.TreeID);
  197. }
  198. }
  199. else
  200. {
  201. status = NTStatus.STATUS_INVALID_SMB;
  202. }
  203. return null;
  204. }
  205. private void OnClientSocketReceive(IAsyncResult ar)
  206. {
  207. if (ar != m_currentAsyncResult)
  208. {
  209. // We ignore calls for old sockets which we no longer use
  210. // See: http://rajputyh.blogspot.co.il/2010/04/solve-exception-message-iasyncresult.html
  211. return;
  212. }
  213. ConnectionState state = (ConnectionState)ar.AsyncState;
  214. if (!m_clientSocket.Connected)
  215. {
  216. return;
  217. }
  218. int numberOfBytesReceived = 0;
  219. try
  220. {
  221. numberOfBytesReceived = m_clientSocket.EndReceive(ar);
  222. }
  223. catch (ObjectDisposedException)
  224. {
  225. Log("[ReceiveCallback] EndReceive ObjectDisposedException");
  226. return;
  227. }
  228. catch (SocketException ex)
  229. {
  230. Log("[ReceiveCallback] EndReceive SocketException: " + ex.Message);
  231. return;
  232. }
  233. if (numberOfBytesReceived == 0)
  234. {
  235. m_isConnected = false;
  236. }
  237. else
  238. {
  239. NBTConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  240. buffer.SetNumberOfBytesReceived(numberOfBytesReceived);
  241. ProcessConnectionBuffer(state);
  242. try
  243. {
  244. m_currentAsyncResult = m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnClientSocketReceive), state);
  245. }
  246. catch (ObjectDisposedException)
  247. {
  248. m_isConnected = false;
  249. Log("[ReceiveCallback] BeginReceive ObjectDisposedException");
  250. }
  251. catch (SocketException ex)
  252. {
  253. m_isConnected = false;
  254. Log("[ReceiveCallback] BeginReceive SocketException: " + ex.Message);
  255. }
  256. }
  257. }
  258. private void ProcessConnectionBuffer(ConnectionState state)
  259. {
  260. NBTConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;
  261. while (receiveBuffer.HasCompletePacket())
  262. {
  263. SessionPacket packet = null;
  264. try
  265. {
  266. packet = receiveBuffer.DequeuePacket();
  267. }
  268. catch (Exception)
  269. {
  270. m_clientSocket.Close();
  271. break;
  272. }
  273. if (packet != null)
  274. {
  275. ProcessPacket(packet, state);
  276. }
  277. }
  278. }
  279. private void ProcessPacket(SessionPacket packet, ConnectionState state)
  280. {
  281. if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  282. {
  283. // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
  284. }
  285. else if (packet is PositiveSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  286. {
  287. }
  288. else if (packet is NegativeSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  289. {
  290. m_clientSocket.Close();
  291. m_isConnected = false;
  292. }
  293. else if (packet is SessionMessagePacket)
  294. {
  295. SMB2Command command;
  296. try
  297. {
  298. command = SMB2Command.ReadResponse(packet.Trailer, 0);
  299. }
  300. catch (Exception ex)
  301. {
  302. Log("Invalid SMB2 response: " + ex.Message);
  303. m_clientSocket.Close();
  304. m_isConnected = false;
  305. return;
  306. }
  307. lock (m_incomingQueueLock)
  308. {
  309. m_incomingQueue.Add(command);
  310. m_incomingQueueEventHandle.Set();
  311. }
  312. }
  313. }
  314. internal SMB2Command WaitForCommand(SMB2CommandName commandName)
  315. {
  316. const int TimeOut = 5000;
  317. Stopwatch stopwatch = new Stopwatch();
  318. stopwatch.Start();
  319. while (stopwatch.ElapsedMilliseconds < TimeOut)
  320. {
  321. lock (m_incomingQueueLock)
  322. {
  323. for (int index = 0; index < m_incomingQueue.Count; index++)
  324. {
  325. SMB2Command command = m_incomingQueue[index];
  326. if (command.CommandName == commandName)
  327. {
  328. m_incomingQueue.RemoveAt(index);
  329. return command;
  330. }
  331. }
  332. }
  333. m_incomingQueueEventHandle.WaitOne(100);
  334. }
  335. return null;
  336. }
  337. private void Log(string message)
  338. {
  339. System.Diagnostics.Debug.Print(message);
  340. }
  341. internal void TrySendCommand(SMB2Command request)
  342. {
  343. request.Header.Credits = 1;
  344. request.Header.MessageID = m_messageID;
  345. request.Header.SessionID = m_sessionID;
  346. TrySendCommand(m_clientSocket, request);
  347. m_messageID++;
  348. }
  349. public static void TrySendCommand(Socket socket, SMB2Command request)
  350. {
  351. SessionMessagePacket packet = new SessionMessagePacket();
  352. packet.Trailer = request.GetBytes();
  353. TrySendPacket(socket, packet);
  354. }
  355. public static void TrySendPacket(Socket socket, SessionPacket packet)
  356. {
  357. try
  358. {
  359. socket.Send(packet.GetBytes());
  360. }
  361. catch (SocketException)
  362. {
  363. }
  364. catch (ObjectDisposedException)
  365. {
  366. }
  367. }
  368. }
  369. }