SMB2Client.cs 16 KB

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