SMB2Client.cs 20 KB

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