SMB2Client.cs 17 KB

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