SMBServer.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. /* Copyright (C) 2014-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.Net;
  10. using System.Net.Sockets;
  11. using System.Threading;
  12. using SMBLibrary.Authentication.GSSAPI;
  13. using SMBLibrary.NetBios;
  14. using SMBLibrary.Services;
  15. using SMBLibrary.SMB1;
  16. using SMBLibrary.SMB2;
  17. using Utilities;
  18. namespace SMBLibrary.Server
  19. {
  20. public partial class SMBServer
  21. {
  22. public static readonly int NetBiosOverTCPPort = 139;
  23. public static readonly int DirectTCPPort = 445;
  24. public const string NTLanManagerDialect = "NT LM 0.12";
  25. public static readonly bool EnableExtendedSecurity = true;
  26. private static readonly int InactivityMonitoringInterval = 30000; // Check every 30 seconds
  27. private SMBShareCollection m_shares; // e.g. Shared folders
  28. private GSSProvider m_securityProvider;
  29. private NamedPipeShare m_services; // Named pipes
  30. private Guid m_serverGuid;
  31. private ConnectionManager m_connectionManager;
  32. private Thread m_sendSMBKeepAliveThread;
  33. private IPAddress m_serverAddress;
  34. private SMBTransportType m_transport;
  35. private bool m_enableSMB1;
  36. private bool m_enableSMB2;
  37. private Socket m_listenerSocket;
  38. private bool m_listening;
  39. private DateTime m_serverStartTime;
  40. public event EventHandler<ConnectionRequestEventArgs> ConnectionRequested;
  41. public event EventHandler<LogEntry> LogEntryAdded;
  42. public SMBServer(SMBShareCollection shares, GSSProvider securityProvider)
  43. {
  44. m_shares = shares;
  45. m_securityProvider = securityProvider;
  46. m_services = new NamedPipeShare(shares.ListShares());
  47. m_serverGuid = Guid.NewGuid();
  48. m_connectionManager = new ConnectionManager();
  49. }
  50. public void Start(IPAddress serverAddress, SMBTransportType transport)
  51. {
  52. Start(serverAddress, transport, true, true);
  53. }
  54. public void Start(IPAddress serverAddress, SMBTransportType transport, bool enableSMB1, bool enableSMB2)
  55. {
  56. Start(serverAddress, transport, enableSMB1, enableSMB2, null);
  57. }
  58. /// <param name="connectionInactivityTimeout">
  59. /// The duration after which an unsolicited ECHO response will be sent if no data has been sent or received.
  60. /// Some broken NATs will reply to TCP KeepAlive even after the client initiating the connection has long gone,
  61. /// to prevent such connections from hanging around indefinitely, this parameter can be used.
  62. /// </param>
  63. /// <exception cref="System.Net.Sockets.SocketException"></exception>
  64. public void Start(IPAddress serverAddress, SMBTransportType transport, bool enableSMB1, bool enableSMB2, TimeSpan? connectionInactivityTimeout)
  65. {
  66. if (!m_listening)
  67. {
  68. Log(Severity.Information, "Starting server");
  69. m_serverAddress = serverAddress;
  70. m_transport = transport;
  71. m_enableSMB1 = enableSMB1;
  72. m_enableSMB2 = enableSMB2;
  73. m_listening = true;
  74. m_serverStartTime = DateTime.Now;
  75. m_listenerSocket = new Socket(m_serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  76. int port = (m_transport == SMBTransportType.DirectTCPTransport ? DirectTCPPort : NetBiosOverTCPPort);
  77. m_listenerSocket.Bind(new IPEndPoint(m_serverAddress, port));
  78. m_listenerSocket.Listen((int)SocketOptionName.MaxConnections);
  79. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  80. if (connectionInactivityTimeout.HasValue)
  81. {
  82. m_sendSMBKeepAliveThread = new Thread(delegate()
  83. {
  84. while (m_listening)
  85. {
  86. Thread.Sleep(InactivityMonitoringInterval);
  87. m_connectionManager.SendSMBKeepAlive(connectionInactivityTimeout.Value);
  88. }
  89. });
  90. m_sendSMBKeepAliveThread.IsBackground = true;
  91. m_sendSMBKeepAliveThread.Start();
  92. }
  93. }
  94. }
  95. public void Stop()
  96. {
  97. Log(Severity.Information, "Stopping server");
  98. m_listening = false;
  99. if (m_sendSMBKeepAliveThread != null)
  100. {
  101. m_sendSMBKeepAliveThread.Abort();
  102. }
  103. SocketUtils.ReleaseSocket(m_listenerSocket);
  104. m_connectionManager.ReleaseAllConnections();
  105. }
  106. // This method accepts new connections
  107. private void ConnectRequestCallback(IAsyncResult ar)
  108. {
  109. Socket listenerSocket = (Socket)ar.AsyncState;
  110. Socket clientSocket;
  111. try
  112. {
  113. clientSocket = listenerSocket.EndAccept(ar);
  114. }
  115. catch (ObjectDisposedException)
  116. {
  117. return;
  118. }
  119. catch (SocketException ex)
  120. {
  121. const int WSAECONNRESET = 10054; // The client may have closed the connection before we start to process the connection request.
  122. const int WSAETIMEDOUT = 10060; // The client did not properly respond after a period of time.
  123. // When we get WSAECONNRESET or WSAETIMEDOUT, we have to continue to accept other connection requests.
  124. // See http://stackoverflow.com/questions/7704417/socket-endaccept-error-10054
  125. if (ex.ErrorCode == WSAECONNRESET || ex.ErrorCode == WSAETIMEDOUT)
  126. {
  127. listenerSocket.BeginAccept(ConnectRequestCallback, listenerSocket);
  128. }
  129. Log(Severity.Debug, "Connection request error {0}", ex.ErrorCode);
  130. return;
  131. }
  132. // Windows will set the TCP keepalive timeout to 120 seconds for an SMB connection
  133. SocketUtils.SetKeepAlive(clientSocket, TimeSpan.FromMinutes(2));
  134. // Disable the Nagle Algorithm for this tcp socket:
  135. clientSocket.NoDelay = true;
  136. IPEndPoint clientEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
  137. EventHandler<ConnectionRequestEventArgs> handler = ConnectionRequested;
  138. bool acceptConnection = true;
  139. if (handler != null)
  140. {
  141. ConnectionRequestEventArgs connectionRequestArgs = new ConnectionRequestEventArgs(clientEndPoint);
  142. handler(this, connectionRequestArgs);
  143. acceptConnection = connectionRequestArgs.Accept;
  144. }
  145. if (acceptConnection)
  146. {
  147. ConnectionState state = new ConnectionState(clientSocket, clientEndPoint, Log);
  148. state.LogToServer(Severity.Verbose, "New connection request accepted");
  149. Thread senderThread = new Thread(delegate()
  150. {
  151. ProcessSendQueue(state);
  152. });
  153. senderThread.IsBackground = true;
  154. senderThread.Start();
  155. try
  156. {
  157. // Direct TCP transport packet is actually an NBT Session Message Packet,
  158. // So in either case (NetBios over TCP or Direct TCP Transport) we will receive an NBT packet.
  159. clientSocket.BeginReceive(state.ReceiveBuffer.Buffer, state.ReceiveBuffer.WriteOffset, state.ReceiveBuffer.AvailableLength, 0, ReceiveCallback, state);
  160. }
  161. catch (ObjectDisposedException)
  162. {
  163. }
  164. catch (SocketException)
  165. {
  166. }
  167. }
  168. else
  169. {
  170. Log(Severity.Verbose, "[{0}:{1}] New connection request rejected", clientEndPoint.Address, clientEndPoint.Port);
  171. clientSocket.Close();
  172. }
  173. listenerSocket.BeginAccept(ConnectRequestCallback, listenerSocket);
  174. }
  175. private void ReceiveCallback(IAsyncResult result)
  176. {
  177. ConnectionState state = (ConnectionState)result.AsyncState;
  178. Socket clientSocket = state.ClientSocket;
  179. if (!m_listening)
  180. {
  181. clientSocket.Close();
  182. return;
  183. }
  184. int numberOfBytesReceived;
  185. try
  186. {
  187. numberOfBytesReceived = clientSocket.EndReceive(result);
  188. }
  189. catch (ObjectDisposedException)
  190. {
  191. state.LogToServer(Severity.Debug, "The connection was terminated");
  192. m_connectionManager.ReleaseConnection(state);
  193. return;
  194. }
  195. catch (SocketException ex)
  196. {
  197. const int WSAECONNRESET = 10054;
  198. if (ex.ErrorCode == WSAECONNRESET)
  199. {
  200. state.LogToServer(Severity.Debug, "The connection was forcibly closed by the remote host");
  201. }
  202. else
  203. {
  204. state.LogToServer(Severity.Debug, "The connection was terminated, Socket error code: {0}", ex.ErrorCode);
  205. }
  206. m_connectionManager.ReleaseConnection(state);
  207. return;
  208. }
  209. if (numberOfBytesReceived == 0)
  210. {
  211. state.LogToServer(Severity.Debug, "The client closed the connection");
  212. m_connectionManager.ReleaseConnection(state);
  213. return;
  214. }
  215. state.UpdateLastReceiveDT();
  216. NBTConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;
  217. receiveBuffer.SetNumberOfBytesReceived(numberOfBytesReceived);
  218. ProcessConnectionBuffer(ref state);
  219. if (clientSocket.Connected)
  220. {
  221. try
  222. {
  223. clientSocket.BeginReceive(state.ReceiveBuffer.Buffer, state.ReceiveBuffer.WriteOffset, state.ReceiveBuffer.AvailableLength, 0, ReceiveCallback, state);
  224. }
  225. catch (ObjectDisposedException)
  226. {
  227. m_connectionManager.ReleaseConnection(state);
  228. }
  229. catch (SocketException)
  230. {
  231. m_connectionManager.ReleaseConnection(state);
  232. }
  233. }
  234. }
  235. private void ProcessConnectionBuffer(ref ConnectionState state)
  236. {
  237. Socket clientSocket = state.ClientSocket;
  238. NBTConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;
  239. while (receiveBuffer.HasCompletePacket())
  240. {
  241. SessionPacket packet = null;
  242. try
  243. {
  244. packet = receiveBuffer.DequeuePacket();
  245. }
  246. catch (Exception ex)
  247. {
  248. state.ClientSocket.Close();
  249. state.LogToServer(Severity.Warning, "Rejected Invalid NetBIOS session packet: {0}", ex.Message);
  250. break;
  251. }
  252. if (packet != null)
  253. {
  254. ProcessPacket(packet, ref state);
  255. }
  256. }
  257. }
  258. private void ProcessPacket(SessionPacket packet, ref ConnectionState state)
  259. {
  260. if (packet is SessionMessagePacket)
  261. {
  262. // Note: To be compatible with SMB2 specifications, we must accept SMB_COM_NEGOTIATE.
  263. // We will disconnect the connection if m_enableSMB1 == false and the client does not support SMB2.
  264. bool acceptSMB1 = (state.Dialect == SMBDialect.NotSet || state.Dialect == SMBDialect.NTLM012);
  265. bool acceptSMB2 = (m_enableSMB2 && (state.Dialect == SMBDialect.NotSet || state.Dialect == SMBDialect.SMB202 || state.Dialect == SMBDialect.SMB210));
  266. if (SMB1Header.IsValidSMB1Header(packet.Trailer))
  267. {
  268. if (!acceptSMB1)
  269. {
  270. state.LogToServer(Severity.Verbose, "Rejected SMB1 message");
  271. state.ClientSocket.Close();
  272. return;
  273. }
  274. SMB1Message message = null;
  275. try
  276. {
  277. message = SMB1Message.GetSMB1Message(packet.Trailer);
  278. }
  279. catch (Exception ex)
  280. {
  281. state.LogToServer(Severity.Warning, "Invalid SMB1 message: " + ex.Message);
  282. state.ClientSocket.Close();
  283. return;
  284. }
  285. state.LogToServer(Severity.Verbose, "SMB1 message received: {0} requests, First request: {1}, Packet length: {2}", message.Commands.Count, message.Commands[0].CommandName.ToString(), packet.Length);
  286. if (state.Dialect == SMBDialect.NotSet && m_enableSMB2)
  287. {
  288. // Check if the client supports SMB 2
  289. List<string> smb2Dialects = SMB2.NegotiateHelper.FindSMB2Dialects(message);
  290. if (smb2Dialects.Count > 0)
  291. {
  292. SMB2Command response = SMB2.NegotiateHelper.GetNegotiateResponse(smb2Dialects, m_securityProvider, state, m_transport, m_serverGuid, m_serverStartTime);
  293. if (state.Dialect != SMBDialect.NotSet)
  294. {
  295. state = new SMB2ConnectionState(state);
  296. m_connectionManager.AddConnection(state);
  297. }
  298. EnqueueResponse(state, response);
  299. return;
  300. }
  301. }
  302. if (m_enableSMB1)
  303. {
  304. ProcessSMB1Message(message, ref state);
  305. }
  306. else
  307. {
  308. // [MS-SMB2] 3.3.5.3.2 If the string is not present in the dialect list and the server does not implement SMB,
  309. // the server MUST disconnect the connection [..] without sending a response.
  310. state.LogToServer(Severity.Verbose, "Rejected SMB1 message");
  311. state.ClientSocket.Close();
  312. }
  313. }
  314. else if (SMB2Header.IsValidSMB2Header(packet.Trailer))
  315. {
  316. if (!acceptSMB2)
  317. {
  318. state.LogToServer(Severity.Verbose, "Rejected SMB2 message");
  319. state.ClientSocket.Close();
  320. return;
  321. }
  322. List<SMB2Command> requestChain;
  323. try
  324. {
  325. requestChain = SMB2Command.ReadRequestChain(packet.Trailer, 0);
  326. }
  327. catch (Exception ex)
  328. {
  329. state.LogToServer(Severity.Warning, "Invalid SMB2 request chain: " + ex.Message);
  330. state.ClientSocket.Close();
  331. return;
  332. }
  333. state.LogToServer(Severity.Verbose, "SMB2 request chain received: {0} requests, First request: {1}, Packet length: {2}", requestChain.Count, requestChain[0].CommandName.ToString(), packet.Length);
  334. ProcessSMB2RequestChain(requestChain, ref state);
  335. }
  336. else
  337. {
  338. state.LogToServer(Severity.Warning, "Invalid SMB message");
  339. state.ClientSocket.Close();
  340. }
  341. }
  342. else if (packet is SessionRequestPacket && m_transport == SMBTransportType.NetBiosOverTCP)
  343. {
  344. PositiveSessionResponsePacket response = new PositiveSessionResponsePacket();
  345. state.SendQueue.Enqueue(response);
  346. }
  347. else if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
  348. {
  349. // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
  350. }
  351. else
  352. {
  353. state.LogToServer(Severity.Warning, "Inappropriate NetBIOS session packet");
  354. state.ClientSocket.Close();
  355. return;
  356. }
  357. }
  358. private void ProcessSendQueue(ConnectionState state)
  359. {
  360. state.LogToServer(Severity.Trace, "Entering ProcessSendQueue");
  361. while (true)
  362. {
  363. SessionPacket response;
  364. bool stopped = !state.SendQueue.TryDequeue(out response);
  365. if (stopped)
  366. {
  367. return;
  368. }
  369. Socket clientSocket = state.ClientSocket;
  370. try
  371. {
  372. byte[] responseBytes = response.GetBytes();
  373. clientSocket.Send(responseBytes);
  374. }
  375. catch (SocketException ex)
  376. {
  377. state.LogToServer(Severity.Debug, "Failed to send packet. SocketException: {0}", ex.Message);
  378. // Note: m_connectionManager contains SMB1ConnectionState or SMB2ConnectionState instances that were constructed from the initial
  379. // ConnectionState instance given to this method. for this reason, we must use state.ClientEndPoint to find and release the connection.
  380. m_connectionManager.ReleaseConnection(state.ClientEndPoint);
  381. return;
  382. }
  383. catch (ObjectDisposedException)
  384. {
  385. state.LogToServer(Severity.Debug, "Failed to send packet. ObjectDisposedException.");
  386. m_connectionManager.ReleaseConnection(state.ClientEndPoint);
  387. return;
  388. }
  389. state.UpdateLastSendDT();
  390. }
  391. }
  392. public List<SessionInformation> GetSessionsInformation()
  393. {
  394. return m_connectionManager.GetSessionsInformation();
  395. }
  396. public void TerminateConnection(IPEndPoint clientEndPoint)
  397. {
  398. m_connectionManager.ReleaseConnection(clientEndPoint);
  399. }
  400. private void Log(Severity severity, string message)
  401. {
  402. // To be thread-safe we must capture the delegate reference first
  403. EventHandler<LogEntry> handler = LogEntryAdded;
  404. if (handler != null)
  405. {
  406. handler(this, new LogEntry(DateTime.Now, severity, "SMB Server", message));
  407. }
  408. }
  409. private void Log(Severity severity, string message, params object[] args)
  410. {
  411. Log(severity, String.Format(message, args));
  412. }
  413. }
  414. }