NTCreateHelper.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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.Services;
  12. using SMBLibrary.SMB1;
  13. using Utilities;
  14. namespace SMBLibrary.Server.SMB1
  15. {
  16. public class NTCreateHelper
  17. {
  18. internal static SMB1Command GetNTCreateResponse(SMB1Header header, NTCreateAndXRequest request, ISMBShare share, SMB1ConnectionState state)
  19. {
  20. bool isExtended = (request.Flags & NTCreateFlags.NT_CREATE_REQUEST_EXTENDED_RESPONSE) > 0;
  21. string path = request.FileName;
  22. if (share is NamedPipeShare)
  23. {
  24. RemoteService service = ((NamedPipeShare)share).GetService(path);
  25. if (service != null)
  26. {
  27. ushort fileID = state.AddOpenedFile(path);
  28. if (isExtended)
  29. {
  30. return CreateResponseExtendedForNamedPipe(fileID);
  31. }
  32. else
  33. {
  34. return CreateResponseForNamedPipe(fileID);
  35. }
  36. }
  37. header.Status = NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
  38. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  39. }
  40. else // FileSystemShare
  41. {
  42. FileSystemShare fileSystemShare = (FileSystemShare)share;
  43. string userName = state.GetConnectedUserName(header.UID);
  44. bool hasWriteAccess = fileSystemShare.HasWriteAccess(userName);
  45. IFileSystem fileSystem = fileSystemShare.FileSystem;
  46. bool forceDirectory = (request.CreateOptions & CreateOptions.FILE_DIRECTORY_FILE) > 0;
  47. bool forceFile = (request.CreateOptions & CreateOptions.FILE_NON_DIRECTORY_FILE) > 0;
  48. if (forceDirectory & (request.CreateDisposition != CreateDisposition.FILE_CREATE &&
  49. request.CreateDisposition != CreateDisposition.FILE_OPEN &&
  50. request.CreateDisposition != CreateDisposition.FILE_OPEN_IF))
  51. {
  52. header.Status = NTStatus.STATUS_INVALID_PARAMETER;
  53. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  54. }
  55. // Windows will try to access named streams (alternate data streams) regardless of the FILE_NAMED_STREAMS flag, we need to prevent this behaviour.
  56. if (path.Contains(":"))
  57. {
  58. // Windows Server 2003 will return STATUS_OBJECT_NAME_NOT_FOUND
  59. header.Status = NTStatus.STATUS_NO_SUCH_FILE;
  60. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  61. }
  62. FileSystemEntry entry = fileSystem.GetEntry(path);
  63. if (request.CreateDisposition == CreateDisposition.FILE_OPEN)
  64. {
  65. if (entry == null)
  66. {
  67. header.Status = NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
  68. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  69. }
  70. if (entry.IsDirectory && forceFile)
  71. {
  72. header.Status = NTStatus.STATUS_FILE_IS_A_DIRECTORY;
  73. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  74. }
  75. if (!entry.IsDirectory && forceDirectory)
  76. {
  77. // Not sure if that's the correct response
  78. header.Status = NTStatus.STATUS_OBJECT_NAME_COLLISION;
  79. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  80. }
  81. }
  82. else if (request.CreateDisposition == CreateDisposition.FILE_CREATE)
  83. {
  84. if (entry != null)
  85. {
  86. // File already exists, fail the request
  87. state.LogToServer(Severity.Debug, "NTCreate: File '{0}' already exist", path);
  88. header.Status = NTStatus.STATUS_OBJECT_NAME_COLLISION;
  89. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  90. }
  91. if (!hasWriteAccess)
  92. {
  93. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  94. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  95. }
  96. try
  97. {
  98. if (forceDirectory)
  99. {
  100. state.LogToServer(Severity.Information, "NTCreate: Creating directory '{0}'", path);
  101. entry = fileSystem.CreateDirectory(path);
  102. }
  103. else
  104. {
  105. state.LogToServer(Severity.Information, "NTCreate: Creating file '{0}'", path);
  106. entry = fileSystem.CreateFile(path);
  107. }
  108. }
  109. catch (IOException ex)
  110. {
  111. ushort errorCode = IOExceptionHelper.GetWin32ErrorCode(ex);
  112. if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION)
  113. {
  114. state.LogToServer(Severity.Debug, "NTCreate: Sharing violation creating '{0}'", path);
  115. header.Status = NTStatus.STATUS_SHARING_VIOLATION;
  116. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  117. }
  118. else
  119. {
  120. state.LogToServer(Severity.Debug, "NTCreate: Error creating '{0}'", path);
  121. header.Status = NTStatus.STATUS_DATA_ERROR;
  122. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  123. }
  124. }
  125. catch (UnauthorizedAccessException)
  126. {
  127. state.LogToServer(Severity.Debug, "NTCreate: Error creating '{0}', Access Denied", path);
  128. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  129. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  130. }
  131. }
  132. else if (request.CreateDisposition == CreateDisposition.FILE_OPEN_IF ||
  133. request.CreateDisposition == CreateDisposition.FILE_OVERWRITE ||
  134. request.CreateDisposition == CreateDisposition.FILE_OVERWRITE_IF ||
  135. request.CreateDisposition == CreateDisposition.FILE_SUPERSEDE)
  136. {
  137. entry = fileSystem.GetEntry(path);
  138. if (entry == null)
  139. {
  140. if (request.CreateDisposition == CreateDisposition.FILE_OVERWRITE)
  141. {
  142. header.Status = NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
  143. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  144. }
  145. if (!hasWriteAccess)
  146. {
  147. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  148. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  149. }
  150. try
  151. {
  152. if (forceDirectory)
  153. {
  154. state.LogToServer(Severity.Information, "NTCreate: Creating directory '{0}'", path);
  155. entry = fileSystem.CreateDirectory(path);
  156. }
  157. else
  158. {
  159. state.LogToServer(Severity.Information, "NTCreate: Creating file '{0}'", path);
  160. entry = fileSystem.CreateFile(path);
  161. }
  162. }
  163. catch (IOException ex)
  164. {
  165. ushort errorCode = IOExceptionHelper.GetWin32ErrorCode(ex);
  166. if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION)
  167. {
  168. header.Status = NTStatus.STATUS_SHARING_VIOLATION;
  169. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  170. }
  171. else
  172. {
  173. header.Status = NTStatus.STATUS_DATA_ERROR;
  174. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  175. }
  176. }
  177. catch (UnauthorizedAccessException)
  178. {
  179. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  180. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  181. }
  182. }
  183. else
  184. {
  185. if (request.CreateDisposition == CreateDisposition.FILE_OVERWRITE ||
  186. request.CreateDisposition == CreateDisposition.FILE_OVERWRITE_IF ||
  187. request.CreateDisposition == CreateDisposition.FILE_SUPERSEDE)
  188. {
  189. if (!hasWriteAccess)
  190. {
  191. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  192. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  193. }
  194. // Truncate the file
  195. try
  196. {
  197. Stream temp = fileSystem.OpenFile(path, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite);
  198. temp.Close();
  199. }
  200. catch (IOException ex)
  201. {
  202. ushort errorCode = IOExceptionHelper.GetWin32ErrorCode(ex);
  203. if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION)
  204. {
  205. header.Status = NTStatus.STATUS_SHARING_VIOLATION;
  206. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  207. }
  208. else
  209. {
  210. header.Status = NTStatus.STATUS_DATA_ERROR;
  211. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  212. }
  213. }
  214. catch (UnauthorizedAccessException)
  215. {
  216. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  217. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  218. }
  219. }
  220. }
  221. }
  222. else
  223. {
  224. throw new InvalidRequestException();
  225. }
  226. FileAccess fileAccess = ToFileAccess(request.DesiredAccess);
  227. FileShare fileShare = ToFileShare(request.ShareAccess);
  228. if (!hasWriteAccess && (fileAccess == FileAccess.Write || fileAccess == FileAccess.ReadWrite))
  229. {
  230. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  231. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  232. }
  233. Stream stream;
  234. bool deleteOnClose = false;
  235. if (fileAccess == (FileAccess)0 || entry.IsDirectory)
  236. {
  237. stream = null;
  238. }
  239. else
  240. {
  241. // When FILE_OPEN_REPARSE_POINT is specified, the operation should continue normally if the file is not a reparse point.
  242. // FILE_OPEN_REPARSE_POINT is a hint that the caller does not intend to actually read the file, with the exception
  243. // of a file copy operation (where the caller will attempt to simply copy the reparse point).
  244. deleteOnClose = (request.CreateOptions & CreateOptions.FILE_DELETE_ON_CLOSE) > 0;
  245. bool openReparsePoint = (request.CreateOptions & CreateOptions.FILE_OPEN_REPARSE_POINT) > 0;
  246. bool disableBuffering = (request.CreateOptions & CreateOptions.FILE_NO_INTERMEDIATE_BUFFERING) > 0;
  247. bool buffered = (request.CreateOptions & CreateOptions.FILE_SEQUENTIAL_ONLY) > 0 && !disableBuffering && !openReparsePoint;
  248. state.LogToServer(Severity.Verbose, "NTCreate: Opening '{0}', Access={1}, Share={2}, Buffered={3}", path, fileAccess, fileShare, buffered);
  249. try
  250. {
  251. stream = fileSystem.OpenFile(path, FileMode.Open, fileAccess, fileShare);
  252. }
  253. catch (IOException ex)
  254. {
  255. ushort errorCode = IOExceptionHelper.GetWin32ErrorCode(ex);
  256. if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION)
  257. {
  258. state.LogToServer(Severity.Debug, "NTCreate: Sharing violation opening '{0}'", path);
  259. header.Status = NTStatus.STATUS_SHARING_VIOLATION;
  260. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  261. }
  262. else
  263. {
  264. state.LogToServer(Severity.Debug, "NTCreate: Sharing violation opening '{0}', Data Error", path);
  265. header.Status = NTStatus.STATUS_DATA_ERROR;
  266. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  267. }
  268. }
  269. catch (UnauthorizedAccessException)
  270. {
  271. state.LogToServer(Severity.Debug, "NTCreate: Sharing violation opening '{0}', Access Denied", path);
  272. header.Status = NTStatus.STATUS_ACCESS_DENIED;
  273. return new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX);
  274. }
  275. if (buffered)
  276. {
  277. stream = new PrefetchedStream(stream);
  278. }
  279. }
  280. ushort fileID = state.AddOpenedFile(path, stream, deleteOnClose);
  281. if (isExtended)
  282. {
  283. NTCreateAndXResponseExtended response = CreateResponseExtendedFromFileSystemEntry(entry, fileID);
  284. if ((request.Flags & NTCreateFlags.NT_CREATE_REQUEST_OPBATCH) > 0)
  285. {
  286. response.OpLockLevel = OpLockLevel.BatchOpLockGranted;
  287. }
  288. return response;
  289. }
  290. else
  291. {
  292. NTCreateAndXResponse response = CreateResponseFromFileSystemEntry(entry, fileID);
  293. if ((request.Flags & NTCreateFlags.NT_CREATE_REQUEST_OPBATCH) > 0)
  294. {
  295. response.OpLockLevel = OpLockLevel.BatchOpLockGranted;
  296. }
  297. return response;
  298. }
  299. }
  300. }
  301. public static FileAccess ToFileAccess(DesiredAccess desiredAccess)
  302. {
  303. if ((desiredAccess & DesiredAccess.GENERIC_ALL) > 0 ||
  304. ((desiredAccess & DesiredAccess.FILE_READ_DATA) > 0 && (desiredAccess & DesiredAccess.FILE_WRITE_DATA) > 0) ||
  305. ((desiredAccess & DesiredAccess.FILE_READ_DATA) > 0 && (desiredAccess & DesiredAccess.FILE_APPEND_DATA) > 0))
  306. {
  307. return FileAccess.ReadWrite;
  308. }
  309. else if ((desiredAccess & DesiredAccess.GENERIC_WRITE) > 0 ||
  310. (desiredAccess & DesiredAccess.FILE_WRITE_DATA) > 0 ||
  311. (desiredAccess & DesiredAccess.FILE_APPEND_DATA) > 0)
  312. {
  313. return FileAccess.Write;
  314. }
  315. else if ((desiredAccess & DesiredAccess.FILE_READ_DATA) > 0)
  316. {
  317. return FileAccess.Read;
  318. }
  319. else
  320. {
  321. return (FileAccess)0;
  322. }
  323. }
  324. public static FileShare ToFileShare(ShareAccess shareAccess)
  325. {
  326. if ((shareAccess & ShareAccess.FILE_SHARE_READ) > 0 && (shareAccess & ShareAccess.FILE_SHARE_WRITE) > 0)
  327. {
  328. return FileShare.ReadWrite;
  329. }
  330. else if ((shareAccess & ShareAccess.FILE_SHARE_WRITE) > 0)
  331. {
  332. return FileShare.Write;
  333. }
  334. else if ((shareAccess & ShareAccess.FILE_SHARE_READ) > 0)
  335. {
  336. return FileShare.Read;
  337. }
  338. else if ((shareAccess & ShareAccess.FILE_SHARE_DELETE) > 0)
  339. {
  340. return FileShare.Delete;
  341. }
  342. else
  343. {
  344. return FileShare.None;
  345. }
  346. }
  347. private static NTCreateAndXResponse CreateResponseForNamedPipe(ushort fileID)
  348. {
  349. NTCreateAndXResponse response = new NTCreateAndXResponse();
  350. response.FID = fileID;
  351. response.CreateDisposition = CreateDisposition.FILE_OPEN;
  352. response.ExtFileAttributes = ExtendedFileAttributes.Normal;
  353. response.ResourceType = ResourceType.FileTypeMessageModePipe;
  354. response.NMPipeStatus.ICount = 255;
  355. response.NMPipeStatus.ReadMode = ReadMode.MessageMode;
  356. response.NMPipeStatus.NamedPipeType = NamedPipeType.MessageNodePipe;
  357. return response;
  358. }
  359. private static NTCreateAndXResponseExtended CreateResponseExtendedForNamedPipe(ushort fileID)
  360. {
  361. NTCreateAndXResponseExtended response = new NTCreateAndXResponseExtended();
  362. response.FID = fileID;
  363. response.CreateDisposition = CreateDisposition.FILE_OPEN;
  364. response.ExtFileAttributes = ExtendedFileAttributes.Normal;
  365. response.ResourceType = ResourceType.FileTypeMessageModePipe;
  366. NamedPipeStatus status = new NamedPipeStatus();
  367. status.ICount = 255;
  368. status.ReadMode = ReadMode.MessageMode;
  369. status.NamedPipeType = NamedPipeType.MessageNodePipe;
  370. response.NMPipeStatus = status;
  371. response.MaximalAccessRights.File = FileAccessMask.FILE_READ_DATA | FileAccessMask.FILE_WRITE_DATA | FileAccessMask.FILE_APPEND_DATA |
  372. FileAccessMask.FILE_READ_EA | FileAccessMask.FILE_WRITE_EA |
  373. FileAccessMask.FILE_EXECUTE |
  374. FileAccessMask.FILE_READ_ATTRIBUTES | FileAccessMask.FILE_WRITE_ATTRIBUTES |
  375. FileAccessMask.DELETE | FileAccessMask.READ_CONTROL | FileAccessMask.WRITE_DAC | FileAccessMask.WRITE_OWNER | FileAccessMask.SYNCHRONIZE;
  376. response.GuestMaximalAccessRights.File = FileAccessMask.FILE_READ_DATA | FileAccessMask.FILE_WRITE_DATA |
  377. FileAccessMask.FILE_READ_EA | FileAccessMask.FILE_WRITE_EA |
  378. FileAccessMask.FILE_READ_ATTRIBUTES | FileAccessMask.FILE_WRITE_ATTRIBUTES |
  379. FileAccessMask.READ_CONTROL | FileAccessMask.SYNCHRONIZE;
  380. return response;
  381. }
  382. private static NTCreateAndXResponse CreateResponseFromFileSystemEntry(FileSystemEntry entry, ushort fileID)
  383. {
  384. NTCreateAndXResponse response = new NTCreateAndXResponse();
  385. if (entry.IsDirectory)
  386. {
  387. response.ExtFileAttributes = ExtendedFileAttributes.Directory;
  388. response.Directory = true;
  389. }
  390. else
  391. {
  392. response.ExtFileAttributes = ExtendedFileAttributes.Normal;
  393. }
  394. response.FID = fileID;
  395. response.CreateDisposition = CreateDisposition.FILE_OPEN;
  396. response.AllocationSize = InfoHelper.GetAllocationSize(entry.Size);
  397. response.EndOfFile = entry.Size;
  398. response.CreateTime = entry.CreationTime;
  399. response.LastAccessTime = entry.LastAccessTime;
  400. response.LastWriteTime = entry.LastWriteTime;
  401. response.LastChangeTime = entry.LastWriteTime;
  402. response.ResourceType = ResourceType.FileTypeDisk;
  403. return response;
  404. }
  405. private static NTCreateAndXResponseExtended CreateResponseExtendedFromFileSystemEntry(FileSystemEntry entry, ushort fileID)
  406. {
  407. NTCreateAndXResponseExtended response = new NTCreateAndXResponseExtended();
  408. if (entry.IsDirectory)
  409. {
  410. response.ExtFileAttributes = ExtendedFileAttributes.Directory;
  411. response.Directory = true;
  412. }
  413. else
  414. {
  415. response.ExtFileAttributes = ExtendedFileAttributes.Normal;
  416. }
  417. response.FID = fileID;
  418. response.CreateTime = entry.CreationTime;
  419. response.LastAccessTime = entry.LastAccessTime;
  420. response.LastWriteTime = entry.LastWriteTime;
  421. response.LastChangeTime = entry.LastWriteTime;
  422. response.CreateDisposition = CreateDisposition.FILE_OPEN;
  423. response.AllocationSize = InfoHelper.GetAllocationSize(entry.Size);
  424. response.EndOfFile = entry.Size;
  425. response.ResourceType = ResourceType.FileTypeDisk;
  426. response.FileStatus = FileStatus.NO_EAS | FileStatus.NO_SUBSTREAMS | FileStatus.NO_REPARSETAG;
  427. response.MaximalAccessRights.File = FileAccessMask.FILE_READ_DATA | FileAccessMask.FILE_WRITE_DATA | FileAccessMask.FILE_APPEND_DATA |
  428. FileAccessMask.FILE_READ_EA | FileAccessMask.FILE_WRITE_EA |
  429. FileAccessMask.FILE_EXECUTE |
  430. FileAccessMask.FILE_READ_ATTRIBUTES | FileAccessMask.FILE_WRITE_ATTRIBUTES |
  431. FileAccessMask.DELETE | FileAccessMask.READ_CONTROL | FileAccessMask.WRITE_DAC | FileAccessMask.WRITE_OWNER | FileAccessMask.SYNCHRONIZE;
  432. response.GuestMaximalAccessRights.File = FileAccessMask.FILE_READ_DATA | FileAccessMask.FILE_WRITE_DATA |
  433. FileAccessMask.FILE_READ_EA | FileAccessMask.FILE_WRITE_EA |
  434. FileAccessMask.FILE_READ_ATTRIBUTES | FileAccessMask.FILE_WRITE_ATTRIBUTES |
  435. FileAccessMask.READ_CONTROL | FileAccessMask.SYNCHRONIZE;
  436. return response;
  437. }
  438. }
  439. }