Transaction2SubcommandHelper.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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.IO;
  10. using System.Text;
  11. using SMBLibrary.SMB1;
  12. using Utilities;
  13. namespace SMBLibrary.Server.SMB1
  14. {
  15. public class Transaction2SubcommandHelper
  16. {
  17. // Windows servers will return "." and ".." when enumerating directory files, Windows clients do not require it.
  18. // It seems that Ubuntu 10.04.4 and 13.10 expect at least one entry in the response (so empty directory listing cause a problem when omitting both).
  19. public const bool IncludeCurrentDirectoryInResults = true;
  20. public const bool IncludeParentDirectoryInResults = true;
  21. internal static Transaction2FindFirst2Response GetSubcommandResponse(SMB1Header header, Transaction2FindFirst2Request subcommand, FileSystemShare share, SMB1ConnectionState state)
  22. {
  23. IFileSystem fileSystem = share.FileSystem;
  24. string path = subcommand.FileName;
  25. // '\Directory' - Get the directory info
  26. // '\Directory\*' - List the directory files
  27. // '\Directory\s*' - List the directory files starting with s (cmd.exe will use this syntax when entering 's' and hitting tab for autocomplete)
  28. // '\Directory\<.inf' (Update driver will use this syntax)
  29. // '\Directory\exefile"*' (cmd.exe will use this syntax when entering an exe without its extension, explorer will use this opening a directory from the run menu)
  30. bool isDirectoryEnumeration = false;
  31. string searchPattern = String.Empty;
  32. if (path.Contains("*") || path.Contains("<"))
  33. {
  34. isDirectoryEnumeration = true;
  35. int separatorIndex = path.LastIndexOf('\\');
  36. searchPattern = path.Substring(separatorIndex + 1);
  37. path = path.Substring(0, separatorIndex + 1);
  38. }
  39. bool exactNameWithoutExtension = searchPattern.Contains("\"");
  40. if (state.OpenSearches.Count > SMB1ConnectionState.MaxSearches)
  41. {
  42. header.Status = NTStatus.STATUS_OS2_NO_MORE_SIDS;
  43. return null;
  44. }
  45. FileSystemEntry entry = fileSystem.GetEntry(path);
  46. if (entry == null)
  47. {
  48. header.Status = NTStatus.STATUS_NO_SUCH_FILE;
  49. return null;
  50. }
  51. List<FileSystemEntry> entries;
  52. if (isDirectoryEnumeration)
  53. {
  54. try
  55. {
  56. entries = fileSystem.ListEntriesInDirectory(path);
  57. }
  58. catch (UnauthorizedAccessException)
  59. {
  60. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  61. return null;
  62. }
  63. if (searchPattern != String.Empty)
  64. {
  65. entries = GetFiltered(entries, searchPattern);
  66. }
  67. if (!exactNameWithoutExtension)
  68. {
  69. if (IncludeParentDirectoryInResults)
  70. {
  71. entries.Insert(0, fileSystem.GetEntry(FileSystem.GetParentDirectory(path)));
  72. entries[0].Name = "..";
  73. }
  74. if (IncludeCurrentDirectoryInResults)
  75. {
  76. entries.Insert(0, fileSystem.GetEntry(path));
  77. entries[0].Name = ".";
  78. }
  79. }
  80. // If no matching entries are found, the server SHOULD fail the request with STATUS_NO_SUCH_FILE.
  81. if (entries.Count == 0)
  82. {
  83. header.Status = NTStatus.STATUS_NO_SUCH_FILE;
  84. return null;
  85. }
  86. }
  87. else
  88. {
  89. entries = new List<FileSystemEntry>();
  90. entries.Add(entry);
  91. }
  92. bool returnResumeKeys = (subcommand.Flags & FindFlags.SMB_FIND_RETURN_RESUME_KEYS) > 0;
  93. int entriesToReturn = Math.Min(subcommand.SearchCount, entries.Count);
  94. // We ignore SearchAttributes
  95. FindInformationList findInformationList = new FindInformationList();
  96. for (int index = 0; index < entriesToReturn; index++)
  97. {
  98. FindInformation infoEntry = InfoHelper.FromFileSystemEntry(entries[index], subcommand.InformationLevel, header.UnicodeFlag, returnResumeKeys);
  99. findInformationList.Add(infoEntry);
  100. if (findInformationList.GetLength(header.UnicodeFlag) > state.GetMaxDataCount(header.PID))
  101. {
  102. findInformationList.RemoveAt(findInformationList.Count - 1);
  103. break;
  104. }
  105. }
  106. int returnCount = findInformationList.Count;
  107. Transaction2FindFirst2Response response = new Transaction2FindFirst2Response();
  108. response.SetFindInformationList(findInformationList, header.UnicodeFlag);
  109. response.EndOfSearch = (returnCount == entries.Count) && (entries.Count <= subcommand.SearchCount);
  110. bool closeAtEndOfSearch = (subcommand.Flags & FindFlags.SMB_FIND_CLOSE_AT_EOS) > 0;
  111. bool closeAfterRequest = (subcommand.Flags & FindFlags.SMB_FIND_CLOSE_AFTER_REQUEST) > 0;
  112. // If [..] the search fit within a single response and SMB_FIND_CLOSE_AT_EOS is set in the Flags field,
  113. // or if SMB_FIND_CLOSE_AFTER_REQUEST is set in the request,
  114. // the server SHOULD return a SID field value of zero.
  115. // This indicates that the search has been closed and is no longer active on the server.
  116. if ((response.EndOfSearch && closeAtEndOfSearch) || closeAfterRequest)
  117. {
  118. response.SID = 0;
  119. }
  120. else
  121. {
  122. response.SID = state.AllocateSearchHandle();
  123. entries.RemoveRange(0, returnCount);
  124. state.OpenSearches.Add(response.SID, entries);
  125. }
  126. return response;
  127. }
  128. // [MS-FSA] 2.1.4.4
  129. // The FileName is string compared with Expression using the following wildcard rules:
  130. // * (asterisk) Matches zero or more characters.
  131. // ? (question mark) Matches a single character.
  132. // DOS_DOT (" quotation mark) Matches either a period or zero characters beyond the name string.
  133. // DOS_QM (> greater than) Matches any single character or, upon encountering a period or end of name string, advances the expression to the end of the set of contiguous DOS_QMs.
  134. // DOS_STAR (< less than) Matches zero or more characters until encountering and matching the final . in the name.
  135. internal static List<FileSystemEntry> GetFiltered(List<FileSystemEntry> entries, string searchPattern)
  136. {
  137. if (searchPattern == String.Empty || searchPattern == "*")
  138. {
  139. return entries;
  140. }
  141. List<FileSystemEntry> result = new List<FileSystemEntry>();
  142. if (searchPattern.EndsWith("*") && searchPattern.Length > 1)
  143. {
  144. string fileNameStart = searchPattern.Substring(0, searchPattern.Length - 1);
  145. bool exactNameWithoutExtensionMatch = false;
  146. if (fileNameStart.EndsWith("\""))
  147. {
  148. exactNameWithoutExtensionMatch = true;
  149. fileNameStart = fileNameStart.Substring(0, fileNameStart.Length - 1);
  150. }
  151. foreach (FileSystemEntry entry in entries)
  152. {
  153. if (!exactNameWithoutExtensionMatch)
  154. {
  155. if (entry.Name.StartsWith(fileNameStart, StringComparison.InvariantCultureIgnoreCase))
  156. {
  157. result.Add(entry);
  158. }
  159. }
  160. else
  161. {
  162. if (entry.Name.StartsWith(fileNameStart + ".", StringComparison.InvariantCultureIgnoreCase) ||
  163. entry.Name.Equals(fileNameStart, StringComparison.InvariantCultureIgnoreCase))
  164. {
  165. result.Add(entry);
  166. }
  167. }
  168. }
  169. }
  170. else if (searchPattern.StartsWith("<"))
  171. {
  172. string fileNameEnd = searchPattern.Substring(1);
  173. foreach (FileSystemEntry entry in entries)
  174. {
  175. if (entry.Name.EndsWith(fileNameEnd, StringComparison.InvariantCultureIgnoreCase))
  176. {
  177. result.Add(entry);
  178. }
  179. }
  180. }
  181. return result;
  182. }
  183. internal static Transaction2FindNext2Response GetSubcommandResponse(SMB1Header header, Transaction2FindNext2Request subcommand, FileSystemShare share, SMB1ConnectionState state)
  184. {
  185. if (!state.OpenSearches.ContainsKey(subcommand.SID))
  186. {
  187. header.Status = NTStatus.STATUS_INVALID_HANDLE;
  188. return null;
  189. }
  190. bool returnResumeKeys = (subcommand.Flags & FindFlags.SMB_FIND_RETURN_RESUME_KEYS) > 0;
  191. List<FileSystemEntry> entries = state.OpenSearches[subcommand.SID];
  192. FindInformationList findInformationList = new FindInformationList();
  193. for (int index = 0; index < entries.Count; index++)
  194. {
  195. FindInformation infoEntry = InfoHelper.FromFileSystemEntry(entries[index], subcommand.InformationLevel, header.UnicodeFlag, returnResumeKeys);
  196. findInformationList.Add(infoEntry);
  197. if (findInformationList.GetLength(header.UnicodeFlag) > state.GetMaxDataCount(header.PID))
  198. {
  199. findInformationList.RemoveAt(findInformationList.Count - 1);
  200. break;
  201. }
  202. }
  203. int returnCount = findInformationList.Count;
  204. Transaction2FindNext2Response response = new Transaction2FindNext2Response();
  205. response.SetFindInformationList(findInformationList, header.UnicodeFlag);
  206. entries.RemoveRange(0, returnCount);
  207. state.OpenSearches[subcommand.SID] = entries;
  208. response.EndOfSearch = (returnCount == entries.Count) && (entries.Count <= subcommand.SearchCount);
  209. if (response.EndOfSearch)
  210. {
  211. state.ReleaseSearchHandle(subcommand.SID);
  212. }
  213. return response;
  214. }
  215. internal static Transaction2QueryFSInformationResponse GetSubcommandResponse(SMB1Header header, Transaction2QueryFSInformationRequest subcommand, FileSystemShare share)
  216. {
  217. Transaction2QueryFSInformationResponse response = new Transaction2QueryFSInformationResponse();
  218. QueryFSInformation queryFSInformation = InfoHelper.GetFSInformation(subcommand.InformationLevel, share.FileSystem);
  219. response.SetQueryFSInformation(queryFSInformation, header.UnicodeFlag);
  220. return response;
  221. }
  222. internal static Transaction2QueryPathInformationResponse GetSubcommandResponse(SMB1Header header, Transaction2QueryPathInformationRequest subcommand, FileSystemShare share, SMB1ConnectionState state)
  223. {
  224. IFileSystem fileSystem = share.FileSystem;
  225. string path = subcommand.FileName;
  226. FileSystemEntry entry = fileSystem.GetEntry(path);
  227. if (entry == null)
  228. {
  229. // Windows Server 2003 will return STATUS_OBJECT_NAME_NOT_FOUND
  230. // Returning STATUS_NO_SUCH_FILE caused an issue when executing ImageX.exe from WinPE 3.0 (32-bit)
  231. state.LogToServer(Severity.Debug, "Transaction2QueryPathInformation: File not found, Path: '{0}'", path);
  232. header.Status = NTStatus.STATUS_OBJECT_NAME_NOT_FOUND;
  233. return null;
  234. }
  235. Transaction2QueryPathInformationResponse response = new Transaction2QueryPathInformationResponse();
  236. QueryInformation queryInformation = InfoHelper.FromFileSystemEntry(entry, subcommand.InformationLevel);
  237. response.SetQueryInformation(queryInformation);
  238. return response;
  239. }
  240. internal static Transaction2QueryFileInformationResponse GetSubcommandResponse(SMB1Header header, Transaction2QueryFileInformationRequest subcommand, FileSystemShare share, SMB1ConnectionState state)
  241. {
  242. IFileSystem fileSystem = share.FileSystem;
  243. string openedFilePath = state.GetOpenedFilePath(subcommand.FID);
  244. if (openedFilePath == null)
  245. {
  246. header.Status = NTStatus.STATUS_INVALID_HANDLE;
  247. return null;
  248. }
  249. FileSystemEntry entry = fileSystem.GetEntry(openedFilePath);
  250. if (entry == null)
  251. {
  252. header.Status = NTStatus.STATUS_NO_SUCH_FILE;
  253. return null;
  254. }
  255. Transaction2QueryFileInformationResponse response = new Transaction2QueryFileInformationResponse();
  256. QueryInformation queryInformation = InfoHelper.FromFileSystemEntry(entry, subcommand.InformationLevel);
  257. response.SetQueryInformation(queryInformation);
  258. return response;
  259. }
  260. internal static Transaction2SetFileInformationResponse GetSubcommandResponse(SMB1Header header, Transaction2SetFileInformationRequest subcommand, FileSystemShare share, SMB1ConnectionState state)
  261. {
  262. string openedFilePath = state.GetOpenedFilePath(subcommand.FID);
  263. if (openedFilePath == null)
  264. {
  265. header.Status = NTStatus.STATUS_INVALID_HANDLE;
  266. return null;
  267. }
  268. OpenedFileObject fileObject = state.GetOpenedFileObject(subcommand.FID);
  269. Transaction2SetFileInformationResponse response = new Transaction2SetFileInformationResponse();
  270. switch (subcommand.InformationLevel)
  271. {
  272. case SetInformationLevel.SMB_INFO_STANDARD:
  273. {
  274. return response;
  275. }
  276. case SetInformationLevel.SMB_INFO_SET_EAS:
  277. {
  278. throw new NotImplementedException();
  279. }
  280. case SetInformationLevel.SMB_SET_FILE_BASIC_INFO:
  281. {
  282. string userName = state.GetConnectedUserName(header.UID);
  283. if (!share.HasWriteAccess(userName))
  284. {
  285. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  286. return null;
  287. }
  288. SetFileBasicInfo info = (SetFileBasicInfo)subcommand.SetInfo;
  289. bool isHidden = (info.ExtFileAttributes & ExtendedFileAttributes.Hidden) > 0;
  290. bool isReadonly = (info.ExtFileAttributes & ExtendedFileAttributes.Readonly) > 0;
  291. bool isArchived = (info.ExtFileAttributes & ExtendedFileAttributes.Archive) > 0;
  292. try
  293. {
  294. share.FileSystem.SetAttributes(openedFilePath, isHidden, isReadonly, isArchived);
  295. }
  296. catch (UnauthorizedAccessException)
  297. {
  298. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  299. return null;
  300. }
  301. DateTime? creationTime = null;
  302. DateTime? lastWriteDT = null;
  303. DateTime? lastAccessTime = null;
  304. if (info.CreationTime != SMB1Helper.FileTimeNotSpecified)
  305. {
  306. creationTime = info.CreationTime;
  307. }
  308. if (info.LastWriteTime != SMB1Helper.FileTimeNotSpecified)
  309. {
  310. lastWriteDT = info.LastWriteTime;
  311. }
  312. if (info.LastAccessTime != SMB1Helper.FileTimeNotSpecified)
  313. {
  314. lastAccessTime = info.LastAccessTime;
  315. }
  316. try
  317. {
  318. share.FileSystem.SetDates(openedFilePath, creationTime, lastWriteDT, lastAccessTime);
  319. }
  320. catch (IOException ex)
  321. {
  322. ushort errorCode = IOExceptionHelper.GetWin32ErrorCode(ex);
  323. if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION)
  324. {
  325. // Returning STATUS_SHARING_VIOLATION is undocumented but apparently valid
  326. state.LogToServer(Severity.Debug, "Transaction2SetFileInformation: Sharing violation setting file dates, Path: '{0}'", openedFilePath);
  327. header.Status = NTStatus.STATUS_SHARING_VIOLATION;
  328. return null;
  329. }
  330. else
  331. {
  332. header.Status = NTStatus.STATUS_DATA_ERROR;
  333. return null;
  334. }
  335. }
  336. catch (UnauthorizedAccessException)
  337. {
  338. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  339. return null;
  340. }
  341. return response;
  342. }
  343. case SetInformationLevel.SMB_SET_FILE_DISPOSITION_INFO:
  344. {
  345. if (((SetFileDispositionInfo)subcommand.SetInfo).DeletePending)
  346. {
  347. // We're supposed to delete the file on close, but it's too late to report errors at this late stage
  348. string userName = state.GetConnectedUserName(header.UID);
  349. if (!share.HasWriteAccess(userName))
  350. {
  351. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  352. return null;
  353. }
  354. if (fileObject.Stream != null)
  355. {
  356. fileObject.Stream.Close();
  357. }
  358. try
  359. {
  360. state.LogToServer(Severity.Information, "NTCreate: Deleting file '{0}'", openedFilePath);
  361. share.FileSystem.Delete(openedFilePath);
  362. }
  363. catch (IOException)
  364. {
  365. state.LogToServer(Severity.Information, "NTCreate: Error deleting '{0}'", openedFilePath);
  366. header.Status = NTStatus.STATUS_SHARING_VIOLATION;
  367. return null;
  368. }
  369. catch (UnauthorizedAccessException)
  370. {
  371. state.LogToServer(Severity.Information, "NTCreate: Error deleting '{0}', Access Denied", openedFilePath);
  372. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  373. return null;
  374. }
  375. }
  376. return response;
  377. }
  378. case SetInformationLevel.SMB_SET_FILE_ALLOCATION_INFO:
  379. {
  380. // This subcommand is used to set the file length in bytes.
  381. // Note: the input will NOT be a multiple of the cluster size / bytes per sector.
  382. ulong allocationSize = ((SetFileAllocationInfo)subcommand.SetInfo).AllocationSize;
  383. try
  384. {
  385. fileObject.Stream.SetLength((long)allocationSize);
  386. }
  387. catch (IOException)
  388. {
  389. state.LogToServer(Severity.Debug, "SMB_SET_FILE_ALLOCATION_INFO: Cannot set allocation for '{0}'", openedFilePath);
  390. }
  391. catch (UnauthorizedAccessException)
  392. {
  393. state.LogToServer(Severity.Debug, "SMB_SET_FILE_ALLOCATION_INFO: Cannot set allocation for '{0}'. Access Denied", openedFilePath);
  394. }
  395. return response;
  396. }
  397. case SetInformationLevel.SMB_SET_FILE_END_OF_FILE_INFO:
  398. {
  399. ulong endOfFile = ((SetFileEndOfFileInfo)subcommand.SetInfo).EndOfFile;
  400. try
  401. {
  402. fileObject.Stream.SetLength((long)endOfFile);
  403. }
  404. catch (IOException)
  405. {
  406. state.LogToServer(Severity.Debug, "SMB_SET_FILE_END_OF_FILE_INFO: Cannot set end of file for '{0}'", openedFilePath);
  407. }
  408. catch (UnauthorizedAccessException)
  409. {
  410. state.LogToServer(Severity.Debug, "SMB_SET_FILE_END_OF_FILE_INFO: Cannot set end of file for '{0}'. Access Denied", openedFilePath);
  411. }
  412. return response;
  413. }
  414. default:
  415. {
  416. throw new InvalidRequestException();
  417. }
  418. }
  419. }
  420. }
  421. }