SMB2Client.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /* Copyright (C) 2017-2018 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. byte[] negotiateMessage = NTLMAuthenticationHelper.GetNegotiateMessage(m_securityBlob, domainName, authenticationMethod);
  124. if (negotiateMessage == null)
  125. {
  126. return NTStatus.SEC_E_INVALID_TOKEN;
  127. }
  128. SessionSetupRequest request = new SessionSetupRequest();
  129. request.SecurityMode = SecurityMode.SigningEnabled;
  130. request.SecurityBuffer = negotiateMessage;
  131. TrySendCommand(request);
  132. SMB2Command response = WaitForCommand(SMB2CommandName.SessionSetup);
  133. if (response != null)
  134. {
  135. if (response.Header.Status == NTStatus.STATUS_MORE_PROCESSING_REQUIRED && response is SessionSetupResponse)
  136. {
  137. byte[] authenticateMessage = NTLMAuthenticationHelper.GetAuthenticateMessage(((SessionSetupResponse)response).SecurityBuffer, domainName, userName, password, authenticationMethod, out m_sessionKey);
  138. if (authenticateMessage == null)
  139. {
  140. return NTStatus.SEC_E_INVALID_TOKEN;
  141. }
  142. m_sessionID = response.Header.SessionID;
  143. request = new SessionSetupRequest();
  144. request.SecurityMode = SecurityMode.SigningEnabled;
  145. request.SecurityBuffer = authenticateMessage;
  146. TrySendCommand(request);
  147. response = WaitForCommand(SMB2CommandName.SessionSetup);
  148. if (response != null)
  149. {
  150. m_isLoggedIn = (response.Header.Status == NTStatus.STATUS_SUCCESS);
  151. return response.Header.Status;
  152. }
  153. }
  154. else
  155. {
  156. return response.Header.Status;
  157. }
  158. }
  159. return NTStatus.STATUS_INVALID_SMB;
  160. }
  161. public NTStatus Logoff()
  162. {
  163. if (!m_isConnected)
  164. {
  165. throw new InvalidOperationException("A login session must be successfully established before attempting logoff");
  166. }
  167. LogoffRequest request = new LogoffRequest();
  168. TrySendCommand(request);
  169. SMB2Command response = WaitForCommand(SMB2CommandName.Logoff);
  170. if (response != null)
  171. {
  172. m_isLoggedIn = (response.Header.Status != NTStatus.STATUS_SUCCESS);
  173. return response.Header.Status;
  174. }
  175. return NTStatus.STATUS_INVALID_SMB;
  176. }
  177. public List<string> ListShares(out NTStatus status)
  178. {
  179. if (!m_isConnected || !m_isLoggedIn)
  180. {
  181. throw new InvalidOperationException("A login session must be successfully established before retrieving share list");
  182. }
  183. ISMBFileStore namedPipeShare = TreeConnect("IPC$", out status);
  184. if (namedPipeShare == null)
  185. {
  186. return null;
  187. }
  188. List<string> shares = ServerServiceHelper.ListShares(namedPipeShare, SMBLibrary.Services.ShareType.DiskDrive, out status);
  189. namedPipeShare.Disconnect();
  190. return shares;
  191. }
  192. public ISMBFileStore TreeConnect(string shareName, out NTStatus status)
  193. {
  194. if (!m_isConnected || !m_isLoggedIn)
  195. {
  196. throw new InvalidOperationException("A login session must be successfully established before connecting to a share");
  197. }
  198. IPAddress serverIPAddress = ((IPEndPoint)m_clientSocket.RemoteEndPoint).Address;
  199. string sharePath = String.Format(@"\\{0}\{1}", serverIPAddress.ToString(), shareName);
  200. TreeConnectRequest request = new TreeConnectRequest();
  201. request.Path = sharePath;
  202. TrySendCommand(request);
  203. SMB2Command response = WaitForCommand(SMB2CommandName.TreeConnect);
  204. if (response != null)
  205. {
  206. status = response.Header.Status;
  207. if (response.Header.Status == NTStatus.STATUS_SUCCESS && response is TreeConnectResponse)
  208. {
  209. return new SMB2FileStore(this, response.Header.TreeID);
  210. }
  211. }
  212. else
  213. {
  214. status = NTStatus.STATUS_INVALID_SMB;
  215. }
  216. return null;
  217. }
  218. private void OnClientSocketReceive(IAsyncResult ar)
  219. {
  220. if (ar != m_currentAsyncResult)
  221. {
  222. // We ignore calls for old sockets which we no longer use
  223. // See: http://rajputyh.blogspot.co.il/2010/04/solve-exception-message-iasyncresult.html
  224. return;
  225. }
  226. ConnectionState state = (ConnectionState)ar.AsyncState;
  227. if (!m_clientSocket.Connected)
  228. {
  229. return;
  230. }
  231. int numberOfBytesReceived = 0;
  232. try
  233. {
  234. numberOfBytesReceived = m_clientSocket.EndReceive(ar);
  235. }
  236. catch (ObjectDisposedException)
  237. {
  238. Log("[ReceiveCallback] EndReceive ObjectDisposedException");
  239. return;
  240. }
  241. catch (SocketException ex)
  242. {
  243. Log("[ReceiveCallback] EndReceive SocketException: " + ex.Message);
  244. return;
  245. }
  246. if (numberOfBytesReceived == 0)
  247. {
  248. m_isConnected = false;
  249. }
  250. else
  251. {
  252. NBTConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  253. buffer.SetNumberOfBytesReceived(numberOfBytesReceived);
  254. ProcessConnectionBuffer(state);
  255. try
  256. {
  257. m_currentAsyncResult = m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnClientSocketReceive), state);
  258. }
  259. catch (ObjectDisposedException)
  260. {
  261. m_isConnected = false;
  262. Log("[ReceiveCallback] BeginReceive ObjectDisposedException");
  263. }
  264. catch (SocketException ex)
  265. {
  266. m_isConnected = false;
  267. Log("[ReceiveCallback] BeginReceive SocketException: " + ex.Message);
  268. }
  269. }
  270. }
  271. private void ProcessConnectionBuffer(ConnectionState state)
  272. {
  273. NBTConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;
  274. while (receiveBuffer.HasCompletePacket())
  275. {
  276. SessionPacket packet = null;
  277. try
  278. {
  279. packet = receiveBuffer.DequeuePacket();
  280. }
  281. catch (Exception)
  282. {
  283. m_clientSocket.Close();
  284. break;
  285. }
  286. if (packet != null)
  287. {
  288. ProcessPacket(packet, state);
  289. }
  290. }
  291. }
  292. private void ProcessPacket(SessionPacket packet, ConnectionState state)
  293. {
  294. if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  295. {
  296. // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
  297. }
  298. else if (packet is PositiveSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  299. {
  300. }
  301. else if (packet is NegativeSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  302. {
  303. m_clientSocket.Close();
  304. m_isConnected = false;
  305. }
  306. else if (packet is SessionMessagePacket)
  307. {
  308. SMB2Command command;
  309. try
  310. {
  311. command = SMB2Command.ReadResponse(packet.Trailer, 0);
  312. }
  313. catch (Exception ex)
  314. {
  315. Log("Invalid SMB2 response: " + ex.Message);
  316. m_clientSocket.Close();
  317. m_isConnected = false;
  318. return;
  319. }
  320. // [MS-SMB2] 3.2.5.1.2 - If the MessageId is 0xFFFFFFFFFFFFFFFF, this is not a reply to a previous request,
  321. // and the client MUST NOT attempt to locate the request, but instead process it as follows:
  322. // If the command field in the SMB2 header is SMB2 OPLOCK_BREAK, it MUST be processed as specified in 3.2.5.19.
  323. // Otherwise, the response MUST be discarded as invalid.
  324. if (command.Header.MessageID != 0xFFFFFFFFFFFFFFFF || command.Header.Command == SMB2CommandName.OplockBreak)
  325. {
  326. lock (m_incomingQueueLock)
  327. {
  328. m_incomingQueue.Add(command);
  329. m_incomingQueueEventHandle.Set();
  330. }
  331. }
  332. }
  333. }
  334. internal SMB2Command WaitForCommand(SMB2CommandName commandName)
  335. {
  336. const int TimeOut = 5000;
  337. Stopwatch stopwatch = new Stopwatch();
  338. stopwatch.Start();
  339. while (stopwatch.ElapsedMilliseconds < TimeOut)
  340. {
  341. lock (m_incomingQueueLock)
  342. {
  343. for (int index = 0; index < m_incomingQueue.Count; index++)
  344. {
  345. SMB2Command command = m_incomingQueue[index];
  346. if (command.CommandName == commandName)
  347. {
  348. m_incomingQueue.RemoveAt(index);
  349. return command;
  350. }
  351. }
  352. }
  353. m_incomingQueueEventHandle.WaitOne(100);
  354. }
  355. return null;
  356. }
  357. private void Log(string message)
  358. {
  359. System.Diagnostics.Debug.Print(message);
  360. }
  361. internal void TrySendCommand(SMB2Command request)
  362. {
  363. request.Header.Credits = 1;
  364. request.Header.MessageID = m_messageID;
  365. request.Header.SessionID = m_sessionID;
  366. TrySendCommand(m_clientSocket, request);
  367. m_messageID++;
  368. }
  369. public uint MaxTransactSize
  370. {
  371. get
  372. {
  373. return m_maxTransactSize;
  374. }
  375. }
  376. public uint MaxReadSize
  377. {
  378. get
  379. {
  380. return m_maxReadSize;
  381. }
  382. }
  383. public uint MaxWriteSize
  384. {
  385. get
  386. {
  387. return m_maxWriteSize;
  388. }
  389. }
  390. public static void TrySendCommand(Socket socket, SMB2Command request)
  391. {
  392. SessionMessagePacket packet = new SessionMessagePacket();
  393. packet.Trailer = request.GetBytes();
  394. TrySendPacket(socket, packet);
  395. }
  396. public static void TrySendPacket(Socket socket, SessionPacket packet)
  397. {
  398. try
  399. {
  400. socket.Send(packet.GetBytes());
  401. }
  402. catch (SocketException)
  403. {
  404. }
  405. catch (ObjectDisposedException)
  406. {
  407. }
  408. }
  409. }
  410. }