SMB1Client.cs 22 KB

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