SMBServer.cs 14 KB

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