SMBServer.cs 16 KB

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