SMBServer.cs 15 KB

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