SMBServer.cs 14 KB

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