SMBServer.cs 16 KB

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