SMB2Client.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /* Copyright (C) 2017-2019 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.Security.Cryptography;
  13. using System.Threading;
  14. using SMBLibrary.Authentication.NTLM;
  15. using SMBLibrary.NetBios;
  16. using SMBLibrary.Services;
  17. using SMBLibrary.SMB2;
  18. using Utilities;
  19. namespace SMBLibrary.Client
  20. {
  21. public class SMB2Client : ISMBClient
  22. {
  23. public const int NetBiosOverTCPPort = 139;
  24. public const int DirectTCPPort = 445;
  25. public const uint ClientMaxTransactSize = 65536;
  26. public const uint ClientMaxReadSize = 65536;
  27. public const uint ClientMaxWriteSize = 65536;
  28. private SMBTransportType m_transport;
  29. private bool m_isConnected;
  30. private bool m_isLoggedIn;
  31. private Socket m_clientSocket;
  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 bool m_signingRequired;
  38. private uint m_maxTransactSize;
  39. private uint m_maxReadSize;
  40. private uint m_maxWriteSize;
  41. private ulong m_sessionID;
  42. private byte[] m_securityBlob;
  43. private byte[] m_sessionKey;
  44. public SMB2Client()
  45. {
  46. }
  47. public bool Connect(IPAddress serverAddress, SMBTransportType transport)
  48. {
  49. m_transport = transport;
  50. if (!m_isConnected)
  51. {
  52. m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  53. int port;
  54. if (transport == SMBTransportType.DirectTCPTransport)
  55. {
  56. port = DirectTCPPort;
  57. }
  58. else
  59. {
  60. port = NetBiosOverTCPPort;
  61. }
  62. try
  63. {
  64. m_clientSocket.Connect(serverAddress, port);
  65. }
  66. catch (SocketException)
  67. {
  68. return false;
  69. }
  70. ConnectionState state = new ConnectionState();
  71. NBTConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  72. m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnClientSocketReceive), state);
  73. bool supportsDialect = NegotiateDialect();
  74. if (!supportsDialect)
  75. {
  76. m_clientSocket.Close();
  77. }
  78. else
  79. {
  80. m_isConnected = true;
  81. }
  82. }
  83. return m_isConnected;
  84. }
  85. public void Disconnect()
  86. {
  87. if (m_isConnected)
  88. {
  89. m_clientSocket.Disconnect(false);
  90. m_isConnected = false;
  91. }
  92. }
  93. private bool NegotiateDialect()
  94. {
  95. NegotiateRequest request = new NegotiateRequest();
  96. request.SecurityMode = SecurityMode.SigningEnabled;
  97. request.ClientGuid = Guid.NewGuid();
  98. request.ClientStartTime = DateTime.Now;
  99. request.Dialects.Add(SMB2Dialect.SMB202);
  100. request.Dialects.Add(SMB2Dialect.SMB210);
  101. TrySendCommand(request);
  102. NegotiateResponse response = WaitForCommand(SMB2CommandName.Negotiate) as NegotiateResponse;
  103. if (response != null && response.Header.Status == NTStatus.STATUS_SUCCESS)
  104. {
  105. m_dialect = response.DialectRevision;
  106. m_signingRequired = (response.SecurityMode & SecurityMode.SigningRequired) > 0;
  107. m_maxTransactSize = Math.Min(response.MaxTransactSize, ClientMaxTransactSize);
  108. m_maxReadSize = Math.Min(response.MaxReadSize, ClientMaxReadSize);
  109. m_maxWriteSize = Math.Min(response.MaxWriteSize, ClientMaxWriteSize);
  110. m_securityBlob = response.SecurityBuffer;
  111. return true;
  112. }
  113. return false;
  114. }
  115. public NTStatus Login(string domainName, string userName, string password)
  116. {
  117. return Login(domainName, userName, password, AuthenticationMethod.NTLMv2);
  118. }
  119. public NTStatus Login(string domainName, string userName, string password, AuthenticationMethod authenticationMethod)
  120. {
  121. if (!m_isConnected)
  122. {
  123. throw new InvalidOperationException("A connection must be successfully established before attempting login");
  124. }
  125. byte[] negotiateMessage = NTLMAuthenticationHelper.GetNegotiateMessage(m_securityBlob, domainName, authenticationMethod);
  126. if (negotiateMessage == null)
  127. {
  128. return NTStatus.SEC_E_INVALID_TOKEN;
  129. }
  130. SessionSetupRequest request = new SessionSetupRequest();
  131. request.SecurityMode = SecurityMode.SigningEnabled;
  132. request.SecurityBuffer = negotiateMessage;
  133. TrySendCommand(request);
  134. SMB2Command response = WaitForCommand(SMB2CommandName.SessionSetup);
  135. if (response != null)
  136. {
  137. if (response.Header.Status == NTStatus.STATUS_MORE_PROCESSING_REQUIRED && response is SessionSetupResponse)
  138. {
  139. byte[] authenticateMessage = NTLMAuthenticationHelper.GetAuthenticateMessage(((SessionSetupResponse)response).SecurityBuffer, domainName, userName, password, authenticationMethod, out m_sessionKey);
  140. if (authenticateMessage == null)
  141. {
  142. return NTStatus.SEC_E_INVALID_TOKEN;
  143. }
  144. m_sessionID = response.Header.SessionID;
  145. request = new SessionSetupRequest();
  146. request.SecurityMode = SecurityMode.SigningEnabled;
  147. request.SecurityBuffer = authenticateMessage;
  148. TrySendCommand(request);
  149. response = WaitForCommand(SMB2CommandName.SessionSetup);
  150. if (response != null)
  151. {
  152. m_isLoggedIn = (response.Header.Status == NTStatus.STATUS_SUCCESS);
  153. return response.Header.Status;
  154. }
  155. }
  156. else
  157. {
  158. return response.Header.Status;
  159. }
  160. }
  161. return NTStatus.STATUS_INVALID_SMB;
  162. }
  163. public NTStatus Logoff()
  164. {
  165. if (!m_isConnected)
  166. {
  167. throw new InvalidOperationException("A login session must be successfully established before attempting logoff");
  168. }
  169. LogoffRequest request = new LogoffRequest();
  170. TrySendCommand(request);
  171. SMB2Command response = WaitForCommand(SMB2CommandName.Logoff);
  172. if (response != null)
  173. {
  174. m_isLoggedIn = (response.Header.Status != NTStatus.STATUS_SUCCESS);
  175. return response.Header.Status;
  176. }
  177. return NTStatus.STATUS_INVALID_SMB;
  178. }
  179. public List<string> ListShares(out NTStatus status)
  180. {
  181. if (!m_isConnected || !m_isLoggedIn)
  182. {
  183. throw new InvalidOperationException("A login session must be successfully established before retrieving share list");
  184. }
  185. ISMBFileStore namedPipeShare = TreeConnect("IPC$", out status);
  186. if (namedPipeShare == null)
  187. {
  188. return null;
  189. }
  190. List<string> shares = ServerServiceHelper.ListShares(namedPipeShare, SMBLibrary.Services.ShareType.DiskDrive, out status);
  191. namedPipeShare.Disconnect();
  192. return shares;
  193. }
  194. public ISMBFileStore TreeConnect(string shareName, out NTStatus status)
  195. {
  196. if (!m_isConnected || !m_isLoggedIn)
  197. {
  198. throw new InvalidOperationException("A login session must be successfully established before connecting to a share");
  199. }
  200. IPAddress serverIPAddress = ((IPEndPoint)m_clientSocket.RemoteEndPoint).Address;
  201. string sharePath = String.Format(@"\\{0}\{1}", serverIPAddress.ToString(), shareName);
  202. TreeConnectRequest request = new TreeConnectRequest();
  203. request.Path = sharePath;
  204. TrySendCommand(request);
  205. SMB2Command response = WaitForCommand(SMB2CommandName.TreeConnect);
  206. if (response != null)
  207. {
  208. status = response.Header.Status;
  209. if (response.Header.Status == NTStatus.STATUS_SUCCESS && response is TreeConnectResponse)
  210. {
  211. return new SMB2FileStore(this, response.Header.TreeID);
  212. }
  213. }
  214. else
  215. {
  216. status = NTStatus.STATUS_INVALID_SMB;
  217. }
  218. return null;
  219. }
  220. private void OnClientSocketReceive(IAsyncResult ar)
  221. {
  222. ConnectionState state = (ConnectionState)ar.AsyncState;
  223. if (!m_clientSocket.Connected)
  224. {
  225. return;
  226. }
  227. int numberOfBytesReceived = 0;
  228. try
  229. {
  230. numberOfBytesReceived = m_clientSocket.EndReceive(ar);
  231. }
  232. catch (ArgumentException) // The IAsyncResult object was not returned from the corresponding synchronous method on this class.
  233. {
  234. return;
  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_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. if (m_signingRequired)
  367. {
  368. request.Header.IsSigned = (m_sessionID != 0 && (request.CommandName == SMB2CommandName.TreeConnect || request.Header.TreeID != 0));
  369. if (request.Header.IsSigned)
  370. {
  371. request.Header.Signature = new byte[16]; // Request could be reused
  372. byte[] buffer = request.GetBytes();
  373. byte[] signature = new HMACSHA256(m_sessionKey).ComputeHash(buffer, 0, buffer.Length);
  374. // [MS-SMB2] The first 16 bytes of the hash MUST be copied into the 16-byte signature field of the SMB2 Header.
  375. request.Header.Signature = ByteReader.ReadBytes(signature, 0, 16);
  376. }
  377. }
  378. TrySendCommand(m_clientSocket, request);
  379. m_messageID++;
  380. }
  381. public uint MaxTransactSize
  382. {
  383. get
  384. {
  385. return m_maxTransactSize;
  386. }
  387. }
  388. public uint MaxReadSize
  389. {
  390. get
  391. {
  392. return m_maxReadSize;
  393. }
  394. }
  395. public uint MaxWriteSize
  396. {
  397. get
  398. {
  399. return m_maxWriteSize;
  400. }
  401. }
  402. public static void TrySendCommand(Socket socket, SMB2Command request)
  403. {
  404. SessionMessagePacket packet = new SessionMessagePacket();
  405. packet.Trailer = request.GetBytes();
  406. TrySendPacket(socket, packet);
  407. }
  408. public static void TrySendPacket(Socket socket, SessionPacket packet)
  409. {
  410. try
  411. {
  412. socket.Send(packet.GetBytes());
  413. }
  414. catch (SocketException)
  415. {
  416. }
  417. catch (ObjectDisposedException)
  418. {
  419. }
  420. }
  421. }
  422. }