SMBServer.SMB2.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /* Copyright (C) 2017-2020 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 SMBLibrary.NetBios;
  10. using SMBLibrary.Server.SMB2;
  11. using SMBLibrary.SMB2;
  12. using Utilities;
  13. namespace SMBLibrary.Server
  14. {
  15. public partial class SMBServer
  16. {
  17. private void ProcessSMB2RequestChain(List<SMB2Command> requestChain, ref ConnectionState state)
  18. {
  19. List<SMB2Command> responseChain = new List<SMB2Command>();
  20. FileID? fileID = null;
  21. NTStatus? fileIDStatus = null;
  22. foreach (SMB2Command request in requestChain)
  23. {
  24. SMB2Command response;
  25. if (request.Header.IsRelatedOperations && RequestContainsFileID(request))
  26. {
  27. if (fileIDStatus != null && fileIDStatus != NTStatus.STATUS_SUCCESS && fileIDStatus != NTStatus.STATUS_BUFFER_OVERFLOW)
  28. {
  29. // [MS-SMB2] When the current request requires a FileId and the previous request either contains
  30. // or generates a FileId, if the previous request fails with an error, the server SHOULD fail the
  31. // current request with the same error code returned by the previous request.
  32. state.LogToServer(Severity.Verbose, "Compunded related request {0} failed because FileId generation failed.", request.CommandName);
  33. response = new ErrorResponse(request.CommandName, fileIDStatus.Value);
  34. }
  35. else if (fileID.HasValue)
  36. {
  37. SetRequestFileID(request, fileID.Value);
  38. response = ProcessSMB2Command(request, ref state);
  39. }
  40. else
  41. {
  42. // [MS-SMB2] When the current request requires a FileId, and if the previous request neither contains
  43. // nor generates a FileId, the server MUST fail the compounded request with STATUS_INVALID_PARAMETER.
  44. state.LogToServer(Severity.Verbose, "Compunded related request {0} failed, the previous request neither contains nor generates a FileId.", request.CommandName);
  45. response = new ErrorResponse(request.CommandName, NTStatus.STATUS_INVALID_PARAMETER);
  46. }
  47. }
  48. else
  49. {
  50. fileID = GetRequestFileID(request);
  51. response = ProcessSMB2Command(request, ref state);
  52. }
  53. if (response != null)
  54. {
  55. UpdateSMB2Header(response, request, state);
  56. responseChain.Add(response);
  57. if (GeneratesFileID(response))
  58. {
  59. fileID = GetResponseFileID(response);
  60. fileIDStatus = response.Header.Status;
  61. }
  62. else if (RequestContainsFileID(request))
  63. {
  64. fileIDStatus = response.Header.Status;
  65. }
  66. }
  67. }
  68. if (responseChain.Count > 0)
  69. {
  70. EnqueueResponseChain(state, responseChain);
  71. }
  72. }
  73. /// <summary>
  74. /// May return null
  75. /// </summary>
  76. private SMB2Command ProcessSMB2Command(SMB2Command command, ref ConnectionState state)
  77. {
  78. if (state.Dialect == SMBDialect.NotSet)
  79. {
  80. if (command is NegotiateRequest)
  81. {
  82. NegotiateRequest request = (NegotiateRequest)command;
  83. SMB2Command response = NegotiateHelper.GetNegotiateResponse(request, m_securityProvider, state, m_transport, m_serverGuid, m_serverStartTime);
  84. if (state.Dialect != SMBDialect.NotSet)
  85. {
  86. state = new SMB2ConnectionState(state);
  87. m_connectionManager.AddConnection(state);
  88. }
  89. return response;
  90. }
  91. else
  92. {
  93. // [MS-SMB2] If the request being received is not an SMB2 NEGOTIATE Request [..]
  94. // and Connection.NegotiateDialect is 0xFFFF or 0x02FF, the server MUST
  95. // disconnect the connection.
  96. state.LogToServer(Severity.Debug, "Invalid Connection State for command {0}", command.CommandName.ToString());
  97. state.ClientSocket.Close();
  98. return null;
  99. }
  100. }
  101. else if (command is NegotiateRequest)
  102. {
  103. // [MS-SMB2] If Connection.NegotiateDialect is 0x0202, 0x0210, 0x0300, 0x0302, or 0x0311,
  104. // the server MUST disconnect the connection.
  105. state.LogToServer(Severity.Debug, "Rejecting NegotiateRequest. NegotiateDialect is already set");
  106. state.ClientSocket.Close();
  107. return null;
  108. }
  109. else
  110. {
  111. return ProcessSMB2Command(command, (SMB2ConnectionState)state);
  112. }
  113. }
  114. private SMB2Command ProcessSMB2Command(SMB2Command command, SMB2ConnectionState state)
  115. {
  116. if (command is SessionSetupRequest)
  117. {
  118. return SessionSetupHelper.GetSessionSetupResponse((SessionSetupRequest)command, m_securityProvider, state);
  119. }
  120. else if (command is EchoRequest)
  121. {
  122. return new EchoResponse();
  123. }
  124. else
  125. {
  126. SMB2Session session = state.GetSession(command.Header.SessionID);
  127. if (session == null)
  128. {
  129. return new ErrorResponse(command.CommandName, NTStatus.STATUS_USER_SESSION_DELETED);
  130. }
  131. if (command is TreeConnectRequest)
  132. {
  133. return TreeConnectHelper.GetTreeConnectResponse((TreeConnectRequest)command, state, m_services, m_shares);
  134. }
  135. else if (command is LogoffRequest)
  136. {
  137. state.LogToServer(Severity.Information, "Logoff: User '{0}' logged off. (SessionID: {1})", session.UserName, command.Header.SessionID);
  138. m_securityProvider.DeleteSecurityContext(ref session.SecurityContext.AuthenticationContext);
  139. state.RemoveSession(command.Header.SessionID);
  140. return new LogoffResponse();
  141. }
  142. else if (command.Header.IsAsync)
  143. {
  144. // TreeID will not be present in an ASYNC header
  145. if (command is CancelRequest)
  146. {
  147. return CancelHelper.GetCancelResponse((CancelRequest)command, state);
  148. }
  149. }
  150. else
  151. {
  152. ISMBShare share = session.GetConnectedTree(command.Header.TreeID);
  153. if (share == null)
  154. {
  155. state.LogToServer(Severity.Verbose, "{0} failed. Invalid TreeID (SessionID: {1}, TreeID: {2}).", command.CommandName, command.Header.SessionID, command.Header.TreeID);
  156. return new ErrorResponse(command.CommandName, NTStatus.STATUS_NETWORK_NAME_DELETED);
  157. }
  158. if (command is TreeDisconnectRequest)
  159. {
  160. return TreeConnectHelper.GetTreeDisconnectResponse((TreeDisconnectRequest)command, share, state);
  161. }
  162. else if (command is CreateRequest)
  163. {
  164. return CreateHelper.GetCreateResponse((CreateRequest)command, share, state);
  165. }
  166. else if (command is QueryInfoRequest)
  167. {
  168. return QueryInfoHelper.GetQueryInfoResponse((QueryInfoRequest)command, share, state);
  169. }
  170. else if (command is SetInfoRequest)
  171. {
  172. return SetInfoHelper.GetSetInfoResponse((SetInfoRequest)command, share, state);
  173. }
  174. else if (command is QueryDirectoryRequest)
  175. {
  176. return QueryDirectoryHelper.GetQueryDirectoryResponse((QueryDirectoryRequest)command, share, state);
  177. }
  178. else if (command is ReadRequest)
  179. {
  180. return ReadWriteResponseHelper.GetReadResponse((ReadRequest)command, share, state);
  181. }
  182. else if (command is WriteRequest)
  183. {
  184. return ReadWriteResponseHelper.GetWriteResponse((WriteRequest)command, share, state);
  185. }
  186. else if (command is LockRequest)
  187. {
  188. return LockHelper.GetLockResponse((LockRequest)command, share, state);
  189. }
  190. else if (command is FlushRequest)
  191. {
  192. return ReadWriteResponseHelper.GetFlushResponse((FlushRequest)command, share, state);
  193. }
  194. else if (command is CloseRequest)
  195. {
  196. return CloseHelper.GetCloseResponse((CloseRequest)command, share, state);
  197. }
  198. else if (command is IOCtlRequest)
  199. {
  200. return IOCtlHelper.GetIOCtlResponse((IOCtlRequest)command, share, state);
  201. }
  202. else if (command is CancelRequest)
  203. {
  204. return CancelHelper.GetCancelResponse((CancelRequest)command, state);
  205. }
  206. else if (command is ChangeNotifyRequest)
  207. {
  208. return ChangeNotifyHelper.GetChangeNotifyInterimResponse((ChangeNotifyRequest)command, share, state);
  209. }
  210. }
  211. }
  212. return new ErrorResponse(command.CommandName, NTStatus.STATUS_NOT_SUPPORTED);
  213. }
  214. internal static void EnqueueResponse(ConnectionState state, SMB2Command response)
  215. {
  216. List<SMB2Command> responseChain = new List<SMB2Command>();
  217. responseChain.Add(response);
  218. EnqueueResponseChain(state, responseChain);
  219. }
  220. private static void EnqueueResponseChain(ConnectionState state, List<SMB2Command> responseChain)
  221. {
  222. byte[] sessionKey = null;
  223. if (state is SMB2ConnectionState)
  224. {
  225. // Note: multiple sessions MAY be multiplexed on the same connection, so theoretically
  226. // we could have compounding unrelated requests from different sessions.
  227. // In practice however this is not a real problem.
  228. ulong sessionID = responseChain[0].Header.SessionID;
  229. if (sessionID != 0)
  230. {
  231. SMB2Session session = ((SMB2ConnectionState)state).GetSession(sessionID);
  232. if (session != null)
  233. {
  234. sessionKey = session.SessionKey;
  235. }
  236. }
  237. }
  238. SessionMessagePacket packet = new SessionMessagePacket();
  239. packet.Trailer = SMB2Command.GetCommandChainBytes(responseChain, sessionKey);
  240. state.SendQueue.Enqueue(packet);
  241. state.LogToServer(Severity.Verbose, "SMB2 response chain queued: Response count: {0}, First response: {1}, Packet length: {2}", responseChain.Count, responseChain[0].CommandName.ToString(), packet.Length);
  242. }
  243. private static void UpdateSMB2Header(SMB2Command response, SMB2Command request, ConnectionState state)
  244. {
  245. response.Header.MessageID = request.Header.MessageID;
  246. response.Header.CreditCharge = request.Header.CreditCharge;
  247. response.Header.Credits = Math.Max((ushort)1, request.Header.Credits);
  248. response.Header.IsRelatedOperations = request.Header.IsRelatedOperations;
  249. response.Header.Reserved = request.Header.Reserved;
  250. if (response.Header.SessionID == 0)
  251. {
  252. response.Header.SessionID = request.Header.SessionID;
  253. }
  254. if (response.Header.TreeID == 0)
  255. {
  256. response.Header.TreeID = request.Header.TreeID;
  257. }
  258. bool signingRequired = false;
  259. if (state is SMB2ConnectionState)
  260. {
  261. SMB2Session session = ((SMB2ConnectionState)state).GetSession(response.Header.SessionID);
  262. if (session != null && session.SigningRequired)
  263. {
  264. signingRequired = true;
  265. }
  266. }
  267. // [MS-SMB2] The server SHOULD sign the message [..] if the request was signed by the client,
  268. // and the response is not an interim response to an asynchronously processed request.
  269. bool isInterimResponse = (response.Header.IsAsync && response.Header.Status == NTStatus.STATUS_PENDING);
  270. response.Header.IsSigned = (request.Header.IsSigned || signingRequired) && !isInterimResponse;
  271. }
  272. private static bool RequestContainsFileID(SMB2Command command)
  273. {
  274. return (command is ChangeNotifyRequest ||
  275. command is CloseRequest ||
  276. command is FlushRequest ||
  277. command is IOCtlRequest ||
  278. command is LockRequest ||
  279. command is QueryDirectoryRequest ||
  280. command is QueryInfoRequest ||
  281. command is ReadRequest ||
  282. command is SetInfoRequest ||
  283. command is WriteRequest);
  284. }
  285. private static FileID? GetRequestFileID(SMB2Command command)
  286. {
  287. if (command is ChangeNotifyRequest)
  288. {
  289. return ((ChangeNotifyRequest)command).FileId;
  290. }
  291. else if (command is CloseRequest)
  292. {
  293. return ((CloseRequest)command).FileId;
  294. }
  295. else if (command is FlushRequest)
  296. {
  297. return ((FlushRequest)command).FileId;
  298. }
  299. else if (command is IOCtlRequest)
  300. {
  301. return ((IOCtlRequest)command).FileId;
  302. }
  303. else if (command is LockRequest)
  304. {
  305. return ((LockRequest)command).FileId;
  306. }
  307. else if (command is QueryDirectoryRequest)
  308. {
  309. return ((QueryDirectoryRequest)command).FileId;
  310. }
  311. else if (command is QueryInfoRequest)
  312. {
  313. return ((QueryInfoRequest)command).FileId;
  314. }
  315. else if (command is ReadRequest)
  316. {
  317. return ((ReadRequest)command).FileId;
  318. }
  319. else if (command is SetInfoRequest)
  320. {
  321. return ((SetInfoRequest)command).FileId;
  322. }
  323. else if (command is WriteRequest)
  324. {
  325. return ((WriteRequest)command).FileId;
  326. }
  327. return null;
  328. }
  329. private static void SetRequestFileID(SMB2Command command, FileID fileID)
  330. {
  331. if (command is ChangeNotifyRequest)
  332. {
  333. ((ChangeNotifyRequest)command).FileId = fileID;
  334. }
  335. else if (command is CloseRequest)
  336. {
  337. ((CloseRequest)command).FileId = fileID;
  338. }
  339. else if (command is FlushRequest)
  340. {
  341. ((FlushRequest)command).FileId = fileID;
  342. }
  343. else if (command is IOCtlRequest)
  344. {
  345. ((IOCtlRequest)command).FileId = fileID;
  346. }
  347. else if (command is LockRequest)
  348. {
  349. ((LockRequest)command).FileId = fileID;
  350. }
  351. else if (command is QueryDirectoryRequest)
  352. {
  353. ((QueryDirectoryRequest)command).FileId = fileID;
  354. }
  355. else if (command is QueryInfoRequest)
  356. {
  357. ((QueryInfoRequest)command).FileId = fileID;
  358. }
  359. else if (command is ReadRequest)
  360. {
  361. ((ReadRequest)command).FileId = fileID;
  362. }
  363. else if (command is SetInfoRequest)
  364. {
  365. ((SetInfoRequest)command).FileId = fileID;
  366. }
  367. else if (command is WriteRequest)
  368. {
  369. ((WriteRequest)command).FileId = fileID;
  370. }
  371. }
  372. private static bool GeneratesFileID(SMB2Command command)
  373. {
  374. return (command.CommandName == SMB2CommandName.Create ||
  375. command.CommandName == SMB2CommandName.IOCtl);
  376. }
  377. private static FileID? GetResponseFileID(SMB2Command command)
  378. {
  379. if (command is CreateResponse)
  380. {
  381. return ((CreateResponse)command).FileId;
  382. }
  383. else if (command is IOCtlResponse)
  384. {
  385. return ((IOCtlResponse)command).FileId;
  386. }
  387. return null;
  388. }
  389. }
  390. }