SMBServer.cs 18 KB

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