SMB2Client.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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.Disconnect(false);
  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(m_clientSocket);
  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. Socket clientSocket = state.ClientSocket;
  263. if (!clientSocket.Connected)
  264. {
  265. return;
  266. }
  267. int numberOfBytesReceived = 0;
  268. try
  269. {
  270. numberOfBytesReceived = clientSocket.EndReceive(ar);
  271. }
  272. catch (ArgumentException) // The IAsyncResult object was not returned from the corresponding synchronous method on this class.
  273. {
  274. return;
  275. }
  276. catch (ObjectDisposedException)
  277. {
  278. Log("[ReceiveCallback] EndReceive ObjectDisposedException");
  279. return;
  280. }
  281. catch (SocketException ex)
  282. {
  283. Log("[ReceiveCallback] EndReceive SocketException: " + ex.Message);
  284. return;
  285. }
  286. if (numberOfBytesReceived == 0)
  287. {
  288. m_isConnected = false;
  289. }
  290. else
  291. {
  292. NBTConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  293. buffer.SetNumberOfBytesReceived(numberOfBytesReceived);
  294. ProcessConnectionBuffer(state);
  295. try
  296. {
  297. clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnClientSocketReceive), state);
  298. }
  299. catch (ObjectDisposedException)
  300. {
  301. m_isConnected = false;
  302. Log("[ReceiveCallback] BeginReceive ObjectDisposedException");
  303. }
  304. catch (SocketException ex)
  305. {
  306. m_isConnected = false;
  307. Log("[ReceiveCallback] BeginReceive SocketException: " + ex.Message);
  308. }
  309. }
  310. }
  311. private void ProcessConnectionBuffer(ConnectionState state)
  312. {
  313. NBTConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;
  314. while (receiveBuffer.HasCompletePacket())
  315. {
  316. SessionPacket packet = null;
  317. try
  318. {
  319. packet = receiveBuffer.DequeuePacket();
  320. }
  321. catch (Exception)
  322. {
  323. state.ClientSocket.Close();
  324. break;
  325. }
  326. if (packet != null)
  327. {
  328. ProcessPacket(packet, state);
  329. }
  330. }
  331. }
  332. private void ProcessPacket(SessionPacket packet, ConnectionState state)
  333. {
  334. if (packet is SessionMessagePacket)
  335. {
  336. SMB2Command command;
  337. try
  338. {
  339. command = SMB2Command.ReadResponse(packet.Trailer, 0);
  340. }
  341. catch (Exception ex)
  342. {
  343. Log("Invalid SMB2 response: " + ex.Message);
  344. state.ClientSocket.Close();
  345. m_isConnected = false;
  346. return;
  347. }
  348. // [MS-SMB2] 3.2.5.1.2 - If the MessageId is 0xFFFFFFFFFFFFFFFF, this is not a reply to a previous request,
  349. // and the client MUST NOT attempt to locate the request, but instead process it as follows:
  350. // If the command field in the SMB2 header is SMB2 OPLOCK_BREAK, it MUST be processed as specified in 3.2.5.19.
  351. // Otherwise, the response MUST be discarded as invalid.
  352. if (command.Header.MessageID != 0xFFFFFFFFFFFFFFFF || command.Header.Command == SMB2CommandName.OplockBreak)
  353. {
  354. lock (m_incomingQueueLock)
  355. {
  356. m_incomingQueue.Add(command);
  357. m_incomingQueueEventHandle.Set();
  358. }
  359. }
  360. }
  361. else if ((packet is PositiveSessionResponsePacket || packet is NegativeSessionResponsePacket) && m_transport == SMBTransportType.NetBiosOverTCP)
  362. {
  363. m_sessionResponsePacket = packet;
  364. m_sessionResponseEventHandle.Set();
  365. }
  366. else if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  367. {
  368. // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
  369. }
  370. else
  371. {
  372. Log("Inappropriate NetBIOS session packet");
  373. state.ClientSocket.Close();
  374. }
  375. }
  376. internal SMB2Command WaitForCommand(SMB2CommandName commandName)
  377. {
  378. const int TimeOut = 5000;
  379. Stopwatch stopwatch = new Stopwatch();
  380. stopwatch.Start();
  381. while (stopwatch.ElapsedMilliseconds < TimeOut)
  382. {
  383. lock (m_incomingQueueLock)
  384. {
  385. for (int index = 0; index < m_incomingQueue.Count; index++)
  386. {
  387. SMB2Command command = m_incomingQueue[index];
  388. if (command.CommandName == commandName)
  389. {
  390. m_incomingQueue.RemoveAt(index);
  391. return command;
  392. }
  393. }
  394. }
  395. m_incomingQueueEventHandle.WaitOne(100);
  396. }
  397. return null;
  398. }
  399. internal SessionPacket WaitForSessionResponsePacket()
  400. {
  401. const int TimeOut = 5000;
  402. Stopwatch stopwatch = new Stopwatch();
  403. stopwatch.Start();
  404. while (stopwatch.ElapsedMilliseconds < TimeOut)
  405. {
  406. if (m_sessionResponsePacket != null)
  407. {
  408. SessionPacket result = m_sessionResponsePacket;
  409. m_sessionResponsePacket = null;
  410. return result;
  411. }
  412. m_sessionResponseEventHandle.WaitOne(100);
  413. }
  414. return null;
  415. }
  416. private void Log(string message)
  417. {
  418. System.Diagnostics.Debug.Print(message);
  419. }
  420. internal void TrySendCommand(SMB2Command request)
  421. {
  422. request.Header.Credits = 1;
  423. request.Header.MessageID = m_messageID;
  424. request.Header.SessionID = m_sessionID;
  425. if (m_signingRequired)
  426. {
  427. request.Header.IsSigned = (m_sessionID != 0 && (request.CommandName == SMB2CommandName.TreeConnect || request.Header.TreeID != 0));
  428. if (request.Header.IsSigned)
  429. {
  430. request.Header.Signature = new byte[16]; // Request could be reused
  431. byte[] buffer = request.GetBytes();
  432. byte[] signature = new HMACSHA256(m_sessionKey).ComputeHash(buffer, 0, buffer.Length);
  433. // [MS-SMB2] The first 16 bytes of the hash MUST be copied into the 16-byte signature field of the SMB2 Header.
  434. request.Header.Signature = ByteReader.ReadBytes(signature, 0, 16);
  435. }
  436. }
  437. TrySendCommand(m_clientSocket, request);
  438. m_messageID++;
  439. }
  440. public uint MaxTransactSize
  441. {
  442. get
  443. {
  444. return m_maxTransactSize;
  445. }
  446. }
  447. public uint MaxReadSize
  448. {
  449. get
  450. {
  451. return m_maxReadSize;
  452. }
  453. }
  454. public uint MaxWriteSize
  455. {
  456. get
  457. {
  458. return m_maxWriteSize;
  459. }
  460. }
  461. public static void TrySendCommand(Socket socket, SMB2Command request)
  462. {
  463. SessionMessagePacket packet = new SessionMessagePacket();
  464. packet.Trailer = request.GetBytes();
  465. TrySendPacket(socket, packet);
  466. }
  467. public static void TrySendPacket(Socket socket, SessionPacket packet)
  468. {
  469. try
  470. {
  471. byte[] packetBytes = packet.GetBytes();
  472. socket.Send(packetBytes);
  473. }
  474. catch (SocketException)
  475. {
  476. }
  477. catch (ObjectDisposedException)
  478. {
  479. }
  480. }
  481. }
  482. }