SMB1Client.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. /* Copyright (C) 2014-2017 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.Threading;
  13. using SMBLibrary.Authentication.NTLM;
  14. using SMBLibrary.NetBios;
  15. using SMBLibrary.Services;
  16. using SMBLibrary.SMB1;
  17. using Utilities;
  18. namespace SMBLibrary.Client
  19. {
  20. public class SMB1Client : ISMBClient
  21. {
  22. public const int NetBiosOverTCPPort = 139;
  23. public const int DirectTCPPort = 445;
  24. public const string NTLanManagerDialect = "NT LM 0.12";
  25. public const ushort ClientMaxBufferSize = 65535; // Valid range: 512 - 65535
  26. public const ushort ClientMaxMpxCount = 1;
  27. private SMBTransportType m_transport;
  28. private bool m_isConnected;
  29. private bool m_isLoggedIn;
  30. private Socket m_clientSocket;
  31. private IAsyncResult m_currentAsyncResult;
  32. private bool m_forceExtendedSecurity;
  33. private bool m_unicode;
  34. private bool m_largeFiles;
  35. private bool m_infoLevelPassthrough;
  36. private bool m_largeRead;
  37. private bool m_largeWrite;
  38. private uint m_serverMaxBufferSize;
  39. private ushort m_maxMpxCount;
  40. private object m_incomingQueueLock = new object();
  41. private List<SMB1Message> m_incomingQueue = new List<SMB1Message>();
  42. private EventWaitHandle m_incomingQueueEventHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
  43. private ushort m_userID;
  44. private byte[] m_serverChallenge;
  45. private byte[] m_securityBlob;
  46. private byte[] m_sessionKey;
  47. public SMB1Client()
  48. {
  49. }
  50. public bool Connect(IPAddress serverAddress, SMBTransportType transport)
  51. {
  52. return Connect(serverAddress, transport, true);
  53. }
  54. public bool Connect(IPAddress serverAddress, SMBTransportType transport, bool forceExtendedSecurity)
  55. {
  56. m_transport = transport;
  57. if (!m_isConnected)
  58. {
  59. m_forceExtendedSecurity = forceExtendedSecurity;
  60. m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  61. int port;
  62. if (transport == SMBTransportType.DirectTCPTransport)
  63. {
  64. port = DirectTCPPort;
  65. }
  66. else
  67. {
  68. port = NetBiosOverTCPPort;
  69. }
  70. try
  71. {
  72. m_clientSocket.Connect(serverAddress, port);
  73. }
  74. catch (SocketException)
  75. {
  76. return false;
  77. }
  78. ConnectionState state = new ConnectionState();
  79. NBTConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  80. m_currentAsyncResult = m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnClientSocketReceive), state);
  81. bool supportsDialect = NegotiateDialect(m_forceExtendedSecurity);
  82. if (!supportsDialect)
  83. {
  84. m_clientSocket.Close();
  85. }
  86. else
  87. {
  88. m_isConnected = true;
  89. }
  90. }
  91. return m_isConnected;
  92. }
  93. public void Disconnect()
  94. {
  95. if (m_isConnected)
  96. {
  97. m_clientSocket.Disconnect(false);
  98. m_isConnected = false;
  99. }
  100. }
  101. private bool NegotiateDialect(bool forceExtendedSecurity)
  102. {
  103. if (m_transport == SMBTransportType.NetBiosOverTCP)
  104. {
  105. SessionRequestPacket sessionRequest = new SessionRequestPacket();
  106. sessionRequest.CalledName = NetBiosUtils.GetMSNetBiosName("*SMBSERVER", NetBiosSuffix.FileServiceService); ;
  107. sessionRequest.CallingName = NetBiosUtils.GetMSNetBiosName(Environment.MachineName, NetBiosSuffix.WorkstationService);
  108. TrySendPacket(m_clientSocket, sessionRequest);
  109. }
  110. NegotiateRequest request = new NegotiateRequest();
  111. request.Dialects.Add(NTLanManagerDialect);
  112. TrySendMessage(request);
  113. SMB1Message reply = WaitForMessage(CommandName.SMB_COM_NEGOTIATE);
  114. if (reply == null)
  115. {
  116. return false;
  117. }
  118. if (reply.Commands[0] is NegotiateResponse && !forceExtendedSecurity)
  119. {
  120. NegotiateResponse response = (NegotiateResponse)reply.Commands[0];
  121. m_unicode = ((response.Capabilities & Capabilities.Unicode) > 0);
  122. m_largeFiles = ((response.Capabilities & Capabilities.LargeFiles) > 0);
  123. bool ntSMB = ((response.Capabilities & Capabilities.NTSMB) > 0);
  124. bool rpc = ((response.Capabilities & Capabilities.RpcRemoteApi) > 0);
  125. bool ntStatusCode = ((response.Capabilities & Capabilities.NTStatusCode) > 0);
  126. m_infoLevelPassthrough = ((response.Capabilities & Capabilities.InfoLevelPassthrough) > 0);
  127. m_largeRead = ((response.Capabilities & Capabilities.LargeRead) > 0);
  128. m_largeWrite = ((response.Capabilities & Capabilities.LargeWrite) > 0);
  129. m_serverMaxBufferSize = response.MaxBufferSize;
  130. m_maxMpxCount = Math.Min(response.MaxMpxCount, ClientMaxMpxCount);
  131. m_serverChallenge = response.Challenge;
  132. return ntSMB && rpc && ntStatusCode;
  133. }
  134. else if (reply.Commands[0] is NegotiateResponseExtended)
  135. {
  136. NegotiateResponseExtended response = (NegotiateResponseExtended)reply.Commands[0];
  137. m_unicode = ((response.Capabilities & Capabilities.Unicode) > 0);
  138. m_largeFiles = ((response.Capabilities & Capabilities.LargeFiles) > 0);
  139. bool ntSMB = ((response.Capabilities & Capabilities.NTSMB) > 0);
  140. bool rpc = ((response.Capabilities & Capabilities.RpcRemoteApi) > 0);
  141. bool ntStatusCode = ((response.Capabilities & Capabilities.NTStatusCode) > 0);
  142. m_infoLevelPassthrough = ((response.Capabilities & Capabilities.InfoLevelPassthrough) > 0);
  143. m_largeRead = ((response.Capabilities & Capabilities.LargeRead) > 0);
  144. m_largeWrite = ((response.Capabilities & Capabilities.LargeWrite) > 0);
  145. m_serverMaxBufferSize = response.MaxBufferSize;
  146. m_maxMpxCount = Math.Min(response.MaxMpxCount, ClientMaxMpxCount);
  147. m_securityBlob = response.SecurityBlob;
  148. return ntSMB && rpc && ntStatusCode;
  149. }
  150. else
  151. {
  152. return false;
  153. }
  154. }
  155. public NTStatus Login(string domainName, string userName, string password)
  156. {
  157. return Login(domainName, userName, password, AuthenticationMethod.NTLMv2);
  158. }
  159. public NTStatus Login(string domainName, string userName, string password, AuthenticationMethod authenticationMethod)
  160. {
  161. if (!m_isConnected)
  162. {
  163. throw new InvalidOperationException("A connection must be successfully established before attempting login");
  164. }
  165. Capabilities clientCapabilities = Capabilities.NTSMB | Capabilities.RpcRemoteApi | Capabilities.NTStatusCode | Capabilities.NTFind;
  166. if (m_unicode)
  167. {
  168. clientCapabilities |= Capabilities.Unicode;
  169. }
  170. if (m_largeFiles)
  171. {
  172. clientCapabilities |= Capabilities.LargeFiles;
  173. }
  174. if (m_largeRead)
  175. {
  176. clientCapabilities |= Capabilities.LargeRead;
  177. }
  178. if (m_serverChallenge != null)
  179. {
  180. SessionSetupAndXRequest request = new SessionSetupAndXRequest();
  181. request.MaxBufferSize = ClientMaxBufferSize;
  182. request.MaxMpxCount = m_maxMpxCount;
  183. request.Capabilities = clientCapabilities;
  184. request.AccountName = userName;
  185. request.PrimaryDomain = domainName;
  186. byte[] clientChallenge = new byte[8];
  187. new Random().NextBytes(clientChallenge);
  188. if (authenticationMethod == AuthenticationMethod.NTLMv1)
  189. {
  190. request.OEMPassword = NTLMCryptography.ComputeLMv1Response(m_serverChallenge, password);
  191. request.UnicodePassword = NTLMCryptography.ComputeNTLMv1Response(m_serverChallenge, password);
  192. }
  193. else if (authenticationMethod == AuthenticationMethod.NTLMv1ExtendedSessionSecurity)
  194. {
  195. // [MS-CIFS] CIFS does not support Extended Session Security because there is no mechanism in CIFS to negotiate Extended Session Security
  196. throw new ArgumentException("SMB Extended Security must be negotiated in order for NTLMv1 Extended Session Security to be used");
  197. }
  198. else // NTLMv2
  199. {
  200. // Note: NTLMv2 over non-extended security session setup is not supported under Windows Vista and later which will return STATUS_INVALID_PARAMETER.
  201. // https://msdn.microsoft.com/en-us/library/ee441701.aspx
  202. // https://msdn.microsoft.com/en-us/library/cc236700.aspx
  203. request.OEMPassword = NTLMCryptography.ComputeLMv2Response(m_serverChallenge, clientChallenge, password, userName, domainName);
  204. NTLMv2ClientChallenge clientChallengeStructure = new NTLMv2ClientChallenge(DateTime.UtcNow, clientChallenge, AVPairUtils.GetAVPairSequence(domainName, Environment.MachineName));
  205. byte[] temp = clientChallengeStructure.GetBytesPadded();
  206. byte[] proofStr = NTLMCryptography.ComputeNTLMv2Proof(m_serverChallenge, temp, password, userName, domainName);
  207. request.UnicodePassword = ByteUtils.Concatenate(proofStr, temp);
  208. }
  209. TrySendMessage(request);
  210. SMB1Message reply = WaitForMessage(CommandName.SMB_COM_SESSION_SETUP_ANDX);
  211. if (reply != null)
  212. {
  213. m_isLoggedIn = (reply.Header.Status == NTStatus.STATUS_SUCCESS);
  214. return reply.Header.Status;
  215. }
  216. return NTStatus.STATUS_INVALID_SMB;
  217. }
  218. else // m_securityBlob != null
  219. {
  220. SessionSetupAndXRequestExtended request = new SessionSetupAndXRequestExtended();
  221. request.MaxBufferSize = ClientMaxBufferSize;
  222. request.MaxMpxCount = m_maxMpxCount;
  223. request.Capabilities = clientCapabilities;
  224. request.SecurityBlob = NTLMAuthenticationHelper.GetNegotiateMessage(m_securityBlob, domainName, authenticationMethod);
  225. TrySendMessage(request);
  226. SMB1Message reply = WaitForMessage(CommandName.SMB_COM_SESSION_SETUP_ANDX);
  227. if (reply != null)
  228. {
  229. if (reply.Header.Status == NTStatus.STATUS_MORE_PROCESSING_REQUIRED && reply.Commands[0] is SessionSetupAndXResponseExtended)
  230. {
  231. SessionSetupAndXResponseExtended response = (SessionSetupAndXResponseExtended)reply.Commands[0];
  232. m_userID = reply.Header.UID;
  233. request = new SessionSetupAndXRequestExtended();
  234. request.MaxBufferSize = ClientMaxBufferSize;
  235. request.MaxMpxCount = m_maxMpxCount;
  236. request.Capabilities = clientCapabilities;
  237. request.SecurityBlob = NTLMAuthenticationHelper.GetAuthenticateMessage(response.SecurityBlob, domainName, userName, password, authenticationMethod, out m_sessionKey);
  238. TrySendMessage(request);
  239. reply = WaitForMessage(CommandName.SMB_COM_SESSION_SETUP_ANDX);
  240. if (reply != null)
  241. {
  242. m_isLoggedIn = (reply.Header.Status == NTStatus.STATUS_SUCCESS);
  243. return reply.Header.Status;
  244. }
  245. }
  246. else
  247. {
  248. return reply.Header.Status;
  249. }
  250. }
  251. return NTStatus.STATUS_INVALID_SMB;
  252. }
  253. }
  254. public NTStatus Logoff()
  255. {
  256. if (!m_isConnected)
  257. {
  258. throw new InvalidOperationException("A login session must be successfully established before attempting logoff");
  259. }
  260. LogoffAndXRequest request = new LogoffAndXRequest();
  261. TrySendMessage(request);
  262. SMB1Message reply = WaitForMessage(CommandName.SMB_COM_LOGOFF_ANDX);
  263. if (reply != null)
  264. {
  265. m_isLoggedIn = (reply.Header.Status != NTStatus.STATUS_SUCCESS);
  266. return reply.Header.Status;
  267. }
  268. return NTStatus.STATUS_INVALID_SMB;
  269. }
  270. public List<string> ListShares(out NTStatus status)
  271. {
  272. if (!m_isConnected || !m_isLoggedIn)
  273. {
  274. throw new InvalidOperationException("A login session must be successfully established before retrieving share list");
  275. }
  276. SMB1FileStore namedPipeShare = TreeConnect("IPC$", ServiceName.NamedPipe, out status);
  277. if (namedPipeShare == null)
  278. {
  279. return null;
  280. }
  281. List<string> shares = ServerServiceHelper.ListShares(namedPipeShare, ShareType.DiskDrive, out status);
  282. namedPipeShare.Disconnect();
  283. return shares;
  284. }
  285. public ISMBFileStore TreeConnect(string shareName, out NTStatus status)
  286. {
  287. return TreeConnect(shareName, ServiceName.AnyType, out status);
  288. }
  289. public SMB1FileStore TreeConnect(string shareName, ServiceName serviceName, out NTStatus status)
  290. {
  291. if (!m_isConnected || !m_isLoggedIn)
  292. {
  293. throw new InvalidOperationException("A login session must be successfully established before connecting to a share");
  294. }
  295. TreeConnectAndXRequest request = new TreeConnectAndXRequest();
  296. request.Path = shareName;
  297. request.Service = serviceName;
  298. TrySendMessage(request);
  299. SMB1Message reply = WaitForMessage(CommandName.SMB_COM_TREE_CONNECT_ANDX);
  300. if (reply != null)
  301. {
  302. status = reply.Header.Status;
  303. if (reply.Header.Status == NTStatus.STATUS_SUCCESS && reply.Commands[0] is TreeConnectAndXResponse)
  304. {
  305. TreeConnectAndXResponse response = (TreeConnectAndXResponse)reply.Commands[0];
  306. return new SMB1FileStore(this, reply.Header.TID);
  307. }
  308. }
  309. else
  310. {
  311. status = NTStatus.STATUS_INVALID_SMB;
  312. }
  313. return null;
  314. }
  315. private void OnClientSocketReceive(IAsyncResult ar)
  316. {
  317. if (ar != m_currentAsyncResult)
  318. {
  319. // We ignore calls for old sockets which we no longer use
  320. // See: http://rajputyh.blogspot.co.il/2010/04/solve-exception-message-iasyncresult.html
  321. return;
  322. }
  323. ConnectionState state = (ConnectionState)ar.AsyncState;
  324. if (!m_clientSocket.Connected)
  325. {
  326. return;
  327. }
  328. int numberOfBytesReceived = 0;
  329. try
  330. {
  331. numberOfBytesReceived = m_clientSocket.EndReceive(ar);
  332. }
  333. catch (ObjectDisposedException)
  334. {
  335. Log("[ReceiveCallback] EndReceive ObjectDisposedException");
  336. return;
  337. }
  338. catch (SocketException ex)
  339. {
  340. Log("[ReceiveCallback] EndReceive SocketException: " + ex.Message);
  341. return;
  342. }
  343. if (numberOfBytesReceived == 0)
  344. {
  345. m_isConnected = false;
  346. }
  347. else
  348. {
  349. NBTConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  350. buffer.SetNumberOfBytesReceived(numberOfBytesReceived);
  351. ProcessConnectionBuffer(state);
  352. try
  353. {
  354. m_currentAsyncResult = m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnClientSocketReceive), state);
  355. }
  356. catch (ObjectDisposedException)
  357. {
  358. m_isConnected = false;
  359. Log("[ReceiveCallback] BeginReceive ObjectDisposedException");
  360. }
  361. catch (SocketException ex)
  362. {
  363. m_isConnected = false;
  364. Log("[ReceiveCallback] BeginReceive SocketException: " + ex.Message);
  365. }
  366. }
  367. }
  368. private void ProcessConnectionBuffer(ConnectionState state)
  369. {
  370. NBTConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;
  371. while (receiveBuffer.HasCompletePacket())
  372. {
  373. SessionPacket packet = null;
  374. try
  375. {
  376. packet = receiveBuffer.DequeuePacket();
  377. }
  378. catch (Exception)
  379. {
  380. m_clientSocket.Close();
  381. break;
  382. }
  383. if (packet != null)
  384. {
  385. ProcessPacket(packet, state);
  386. }
  387. }
  388. }
  389. private void ProcessPacket(SessionPacket packet, ConnectionState state)
  390. {
  391. if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  392. {
  393. // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
  394. }
  395. else if (packet is PositiveSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  396. {
  397. }
  398. else if (packet is NegativeSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  399. {
  400. m_clientSocket.Close();
  401. m_isConnected = false;
  402. }
  403. else if (packet is SessionMessagePacket)
  404. {
  405. SMB1Message message;
  406. try
  407. {
  408. message = SMB1Message.GetSMB1Message(packet.Trailer);
  409. }
  410. catch (Exception ex)
  411. {
  412. Log("Invalid SMB1 message: " + ex.Message);
  413. m_clientSocket.Close();
  414. m_isConnected = false;
  415. return;
  416. }
  417. // [MS-CIFS] 3.2.5.1 - If the MID value is the reserved value 0xFFFF, the message can be an OpLock break
  418. // sent by the server. Otherwise, if the PID and MID values of the received message are not found in the
  419. // Client.Connection.PIDMIDList, the message MUST be discarded.
  420. if ((message.Header.MID == 0xFFFF && message.Header.Command == CommandName.SMB_COM_LOCKING_ANDX) ||
  421. (message.Header.PID == 0 && message.Header.MID == 0))
  422. {
  423. lock (m_incomingQueueLock)
  424. {
  425. m_incomingQueue.Add(message);
  426. m_incomingQueueEventHandle.Set();
  427. }
  428. }
  429. }
  430. }
  431. internal SMB1Message WaitForMessage(CommandName commandName)
  432. {
  433. const int TimeOut = 5000;
  434. Stopwatch stopwatch = new Stopwatch();
  435. stopwatch.Start();
  436. while (stopwatch.ElapsedMilliseconds < TimeOut)
  437. {
  438. lock (m_incomingQueueLock)
  439. {
  440. for (int index = 0; index < m_incomingQueue.Count; index++)
  441. {
  442. SMB1Message message = m_incomingQueue[index];
  443. if (message.Commands[0].CommandName == commandName)
  444. {
  445. m_incomingQueue.RemoveAt(index);
  446. return message;
  447. }
  448. }
  449. }
  450. m_incomingQueueEventHandle.WaitOne(100);
  451. }
  452. return null;
  453. }
  454. private void Log(string message)
  455. {
  456. System.Diagnostics.Debug.Print(message);
  457. }
  458. internal void TrySendMessage(SMB1Command request)
  459. {
  460. TrySendMessage(request, 0);
  461. }
  462. internal void TrySendMessage(SMB1Command request, ushort treeID)
  463. {
  464. SMB1Message message = new SMB1Message();
  465. message.Header.UnicodeFlag = m_unicode;
  466. message.Header.ExtendedSecurityFlag = m_forceExtendedSecurity;
  467. message.Header.Flags2 |= HeaderFlags2.LongNamesAllowed | HeaderFlags2.LongNameUsed | HeaderFlags2.NTStatusCode;
  468. message.Header.UID = m_userID;
  469. message.Header.TID = treeID;
  470. message.Commands.Add(request);
  471. TrySendMessage(m_clientSocket, message);
  472. }
  473. public bool Unicode
  474. {
  475. get
  476. {
  477. return m_unicode;
  478. }
  479. }
  480. public bool LargeFiles
  481. {
  482. get
  483. {
  484. return m_largeFiles;
  485. }
  486. }
  487. public bool InfoLevelPassthrough
  488. {
  489. get
  490. {
  491. return m_infoLevelPassthrough;
  492. }
  493. }
  494. public bool LargeRead
  495. {
  496. get
  497. {
  498. return m_largeRead;
  499. }
  500. }
  501. public bool LargeWrite
  502. {
  503. get
  504. {
  505. return m_largeWrite;
  506. }
  507. }
  508. public uint ServerMaxBufferSize
  509. {
  510. get
  511. {
  512. return m_serverMaxBufferSize;
  513. }
  514. }
  515. public int MaxMpxCount
  516. {
  517. get
  518. {
  519. return m_maxMpxCount;
  520. }
  521. }
  522. public uint MaxReadSize
  523. {
  524. get
  525. {
  526. return ClientMaxBufferSize - (SMB1Header.Length + 3 + ReadAndXResponse.ParametersLength);
  527. }
  528. }
  529. public uint MaxWriteSize
  530. {
  531. get
  532. {
  533. uint result = ServerMaxBufferSize - (SMB1Header.Length + 3 + WriteAndXRequest.ParametersFixedLength + 4);
  534. if (m_unicode)
  535. {
  536. result--;
  537. }
  538. return result;
  539. }
  540. }
  541. public static void TrySendMessage(Socket socket, SMB1Message message)
  542. {
  543. SessionMessagePacket packet = new SessionMessagePacket();
  544. packet.Trailer = message.GetBytes();
  545. TrySendPacket(socket, packet);
  546. }
  547. public static void TrySendPacket(Socket socket, SessionPacket packet)
  548. {
  549. try
  550. {
  551. socket.Send(packet.GetBytes());
  552. }
  553. catch (SocketException)
  554. {
  555. }
  556. catch (ObjectDisposedException)
  557. {
  558. }
  559. }
  560. }
  561. }