SMB2Client.cs 22 KB

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