NTCreateHelper.cs 24 KB

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