/// <summary> /// 设置Everyone的写入权限 /// </summary> static void SetControls(FileInfo file) { var everyOneIdentity = new NTAccount("Everyone"); var everyoneAce = new FileSystemAccessRule(everyOneIdentity, FileSystemRights.Write, AccessControlType.Allow); var securityDescriptor = new FileSecurity(); securityDescriptor.SetAccessRule(everyoneAce); file.SetAccessControl(securityDescriptor); }
/// <inheritdoc cref="File.Create(string,int,FileOptions,FileSecurity)"/> public abstract Stream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity);
public override Int32 Create( String FileName, UInt32 CreateOptions, UInt32 GrantedAccess, UInt32 FileAttributes, Byte[] SecurityDescriptor, UInt64 AllocationSize, out Object FileNode, out Object FileDesc0, out FileInfo FileInfo, out String NormalizedName) { FileDesc FileDesc = null; try { FileName = ConcatPath(FileName); if (0 == (CreateOptions & FILE_DIRECTORY_FILE)) { FileSecurity Security = null; if (null != SecurityDescriptor) { Security = new FileSecurity(); Security.SetSecurityDescriptorBinaryForm(SecurityDescriptor); } FileDesc = new FileDesc( new FileStream( FileName, FileMode.CreateNew, (FileSystemRights)GrantedAccess | FileSystemRights.WriteAttributes, FileShare.Read | FileShare.Write | FileShare.Delete, 4096, 0, Security)); } else { if (Directory.Exists(FileName)) { ThrowIoExceptionWithNtStatus(STATUS_OBJECT_NAME_COLLISION); } DirectorySecurity Security = null; if (null != SecurityDescriptor) { Security = new DirectorySecurity(); Security.SetSecurityDescriptorBinaryForm(SecurityDescriptor); } FileDesc = new FileDesc( Directory.CreateDirectory(FileName, Security)); } FileDesc.SetFileAttributes(FileAttributes); FileNode = default(Object); FileDesc0 = FileDesc; NormalizedName = default(String); return(FileDesc.GetFileInfo(out FileInfo)); } catch { if (null != FileDesc && null != FileDesc.Stream) { FileDesc.Stream.Dispose(); } throw; } }
public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { var fileStream = Create(path, bufferSize, options); fileStream.SetAccessControl(fileSecurity); return(fileStream); }
public static void SetAccessControl(FileStream fileStream, FileSecurity fileSecurity) { fileStream.SetAccessControl(fileSecurity); }
/// <summary> /// Sets the permissions to match the template on the specified directory. /// </summary> public void SetPermissions(string template, Uri url, bool exactMatch) { if (url == null) { throw new ArgumentException("Target URI is not valid.", "target"); } string filePath = Utils.GetAbsoluteFilePath(m_directory.FullName + "\\" + template + m_FileExtension, false, false, false); // nothing more to do if no file. if (filePath == null) { return; } string urlMask = null; if (!exactMatch) { urlMask = url.Scheme; urlMask += "://+:"; urlMask += url.Port; urlMask += url.PathAndQuery; if (!urlMask.EndsWith("/")) { urlMask += "/"; } } else { urlMask = url.ToString(); } FileInfo templateFile = new FileInfo(filePath); FileSecurity security1 = templateFile.GetAccessControl(AccessControlSections.Access); List <HttpAccessRule> httpRules = new List <HttpAccessRule>(); foreach (AuthorizationRule rule in security1.GetAccessRules(true, true, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { HttpAccessRule httpRule = new HttpAccessRule(); httpRule.UrlPrefix = urlMask; httpRule.IdentityName = fsr.IdentityReference.Translate(typeof(NTAccount)).ToString(); httpRules.Add(httpRule); if ((fsr.FileSystemRights & FileSystemRights.ChangePermissions) != 0) { httpRule.Right = ApplicationAccessRight.Configure; } else if ((fsr.FileSystemRights & FileSystemRights.WriteData) != 0) { httpRule.Right = ApplicationAccessRight.Update; } else if ((fsr.FileSystemRights & FileSystemRights.ReadData) != 0) { httpRule.Right = ApplicationAccessRight.Run; } } } HttpAccessRule.SetAccessRules(urlMask, httpRules, true); }
public override void SetAccessControl(FileSecurity fileSecurity) { instance.SetAccessControl(fileSecurity); }
public static void SetAccessControl(FileInfo fileInfo, FileSecurity fileSecurity);
public override void SetAccessControl(FileSecurity fileSecurity) { mockFileSystem.File.SetAccessControl(this.path, fileSecurity); }
public virtual void EndGetAccessControl(FileSecurity result, string path, AccessControlSections includeSections) { }
public virtual void EndGetAccessControl(FileSecurity result, string path) { }
public virtual void FailCreate(ref Exception exception, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { }
public virtual void EndCreate(FileStream result, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { }
public virtual void BeginCreate(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { }
[System.Security.SecuritySafeCritical] // auto-generated public void SetAccessControl(FileSecurity fileSecurity) { if (fileSecurity == null) throw new ArgumentNullException("fileSecurity"); Contract.EndContractBlock(); if (_handle.IsClosed) __Error.FileNotOpen(); fileSecurity.Persist(_handle, _fileName); }
public abstract void SetAccessControl(string path, FileSecurity fileSecurity);
/// <summary> /// Creates a new File Object. /// </summary> /// <param name="folderId"></param> /// <param name="name"></param> /// <param name="createdBy"></param> /// <param name="inheritSecurity"></param> /// <returns></returns> public static File Create(Guid? folderId, string name, SecurityObject createdBy, bool inheritSecurity = true) { using (var context = new OnlineFilesEntities()) { if (folderId == null) throw new Exception("Bad Guid."); var folder = context.Folders .Include(x => x.FolderSecurities) .FirstOrDefault(d => d.pk_FolderId == folderId); if (folder == null) throw new Exception("Folder Not Found."); if (!folder.FolderSecurities.Any(x => createdBy.mySecurityGroups.Contains(x.SecurityObjectId) && x.canCreateFiles)) throw new SecurityException("No Access."); var file = new File { fk_FolderId = (Guid) folderId, IsDeleted = false, isRevisioned = true, Name = name, MimeType = MimeMapping.GetMimeMapping(name), CreatedById = createdBy.SecurityObjectId, CreateDt = DateTime.Now, OwnerId = createdBy.SecurityObjectId }; context.Files.Add(file); context.SaveChanges(); FileSecurity fileSecurity = new FileSecurity { CanDelete = true, canRead = true, canWrite = true, fk_FileId = file.pk_FileId, SecurityObjectId = createdBy.SecurityObjectId }; context.FileSecurities.Add(fileSecurity); context.SaveChanges(); foreach (FolderSecurity security in folder.FolderSecurities) { fileSecurity = context.FileSecurities.FirstOrDefault(d => d.SecurityObjectId == security.SecurityObjectId && d.fk_FileId == file.pk_FileId); if (fileSecurity == null) { fileSecurity = new FileSecurity { CanDelete = security.canDelete, canRead = security.canListObjects, canWrite = security.canCreateFiles, fk_FileId = file.pk_FileId, SecurityObjectId = security.SecurityObjectId }; context.FileSecurities.Add(fileSecurity); } else { fileSecurity.CanDelete = security.canDelete; fileSecurity.canRead = security.canListObjects; fileSecurity.canWrite = security.canCreateFiles; } } context.SaveChanges(); return file; } }
public void SetAccessControl(FileSecurity fileSecurity, AccessControlSections includeSections) { File.SetAccessControlInternal(LongFullName, null, fileSecurity, includeSections, PathFormat.LongFullPath); }
[System.Security.SecuritySafeCritical] // auto-generated private unsafe static Win32Native.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share, FileSecurity fileSecurity, out Object pinningHandle) { pinningHandle = null; Win32Native.SECURITY_ATTRIBUTES secAttrs = null; if ((share & FileShare.Inheritable) != 0 || fileSecurity != null) { secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); if ((share & FileShare.Inheritable) != 0) { secAttrs.bInheritHandle = 1; } // For ACL's, get the security descriptor from the FileSecurity. if (fileSecurity != null) { byte[] sd = fileSecurity.GetSecurityDescriptorBinaryForm(); pinningHandle = GCHandle.Alloc(sd, GCHandleType.Pinned); fixed(byte* pSecDescriptor = sd) secAttrs.pSecurityDescriptor = pSecDescriptor; } } return secAttrs; }
private void ConvertFiles(DoWorkEventArgs e, DirectoryInfo source, DirectoryInfo target) { _fileReader.FallbackOnWriterError = _fallbackOnWriterError; if (e.Cancel) { return; } if (_worker.CancellationPending) { e.Cancel = true; return; } ConverterOptions options = this.Options; IEnumerable <string> fileIterator = DirectoryUtils.FindFiles( source, "*.*", SearchOption.TopDirectoryOnly); foreach (string svgFileName in fileIterator) { if (_worker.CancellationPending) { e.Cancel = true; break; } string fileExt = Path.GetExtension(svgFileName); if (string.Equals(fileExt, ".svg", StringComparison.OrdinalIgnoreCase) || string.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase)) { try { FileAttributes fileAttr = File.GetAttributes(svgFileName); if (!_includeHidden) { if ((fileAttr & FileAttributes.Hidden) == FileAttributes.Hidden) { continue; } } FileSecurity security = null; if (_includeSecurity) { security = File.GetAccessControl(svgFileName); } if (_worker.CancellationPending) { e.Cancel = true; break; } DrawingGroup drawing = _fileReader.Read(svgFileName, target); if (drawing == null) { if (_continueOnError) { throw new InvalidOperationException( "The conversion failed due to unknown error."); } } if (options.SaveXaml) { string xamlFile = _fileReader.XamlFile; if (!string.IsNullOrWhiteSpace(xamlFile) && File.Exists(xamlFile)) { File.SetAttributes(xamlFile, fileAttr); // if required to set the security or access control if (_includeSecurity) { File.SetAccessControl(xamlFile, security); } } } if (options.SaveZaml) { string zamlFile = _fileReader.ZamlFile; if (!string.IsNullOrWhiteSpace(zamlFile) && File.Exists(zamlFile)) { File.SetAttributes(zamlFile, fileAttr); // if required to set the security or access control if (_includeSecurity) { File.SetAccessControl(zamlFile, security); } } } if (drawing != null && options.GenerateImage) { _fileReader.SaveImage(svgFileName, target, options.EncoderType); string imageFile = _fileReader.ImageFile; if (!string.IsNullOrWhiteSpace(imageFile) && File.Exists(imageFile)) { File.SetAttributes(imageFile, fileAttr); // if required to set the security or access control if (_includeSecurity) { File.SetAccessControl(imageFile, security); } } } if (drawing != null) { _convertedCount++; } if (_fileReader.WriterErrorOccurred) { _writerErrorOccurred = true; } } catch (Exception ex) { _errorFiles.Add(svgFileName); if (_continueOnError) { StringBuilder builder = new StringBuilder(); builder.AppendLine("Error converting: " + svgFileName); builder.AppendFormat("Error: Exception ({0})", ex.GetType()); builder.AppendLine(); builder.AppendLine(ex.Message); builder.AppendLine(ex.ToString()); _worker.ReportProgress(0, builder.ToString()); } else { throw; } } } } }
/// <summary> /// Sets the permissions to match the template on the specified directory. /// </summary> public void SetPermissions(string template, DirectoryInfo target, bool recursive) { if (target == null || !target.Exists) { throw new ArgumentException("Target directory does not exist.", "target"); } string filePath = Utils.GetAbsoluteFilePath(m_directory.FullName + "\\" + template + m_FileExtension, false, false, false); // nothing more to do if no file. if (filePath == null) { return; } FileInfo templateFile = new FileInfo(filePath); FileSecurity security1 = templateFile.GetAccessControl(AccessControlSections.Access); DirectorySecurity security2 = target.GetAccessControl(AccessControlSections.Access); foreach (AuthorizationRule rule in security2.GetAccessRules(true, true, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { security2.RemoveAccessRule(fsr); } } foreach (AuthorizationRule rule in security1.GetAccessRules(true, true, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { FileSystemAccessRule copy = new FileSystemAccessRule( fsr.IdentityReference, fsr.FileSystemRights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, fsr.AccessControlType); security2.AddAccessRule(copy); } } security2.SetAccessRuleProtection(true, false); target.SetAccessControl(security2); if (recursive) { foreach (DirectoryInfo directory in target.GetDirectories()) { InheritPermissions(directory); } foreach (FileInfo file in target.GetFiles()) { InheritPermissions(file); } } }
public FileStream Create(int bufferSize, FileOptions options, FileSecurity fileSecurity) { return(new FileStream(Path, FileMode.Create, FileSystemRights.Read | FileSystemRights.Write, FileShare.None, bufferSize, options, fileSecurity)); }
public static void SetAccessControl(FileInfo fileInfo, FileSecurity fileSecurity) { fileInfo.SetAccessControl(fileSecurity); }
public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes, FileSecurity security) : this(File.CreateFileCore(transaction, path, attributes, security, mode, access, share, true, false, PathFormat.RelativePath), access) { }
/// <summary> /// Sets the access control. /// </summary> /// <param name="path">The path.</param> /// <param name="fileSecurity">The file security.</param> public override void SetAccessControl( string path, FileSecurity fileSecurity) { }
public override ActionOutcome Go(TVRenameStats stats) { // read NTFS permissions (if any) FileSecurity security = null; try { security = From.GetAccessControl(); } catch { // ignored } try { //we use a temp name just in case we are interrupted or some other problem occurs string tempName = TempFor(To); // If both full filenames are the same then we want to move it away and back //This deals with an issue on some systems (XP?) that case insensitive moves did not occur if (IsMoveRename() || FileHelper.Same(From, To)) { // This step could be slow, so report progress CopyMoveResult moveResult = File.Move(From.FullName, tempName, MoveOptions.CopyAllowed | MoveOptions.ReplaceExisting, CopyProgressCallback, null); if (moveResult.ErrorCode != 0) { throw new TheTVDB.TVDBException(moveResult.ErrorMessage); } } else { //we are copying Debug.Assert(Operation == Op.copy); // This step could be slow, so report progress CopyMoveResult copyResult = File.Copy(From.FullName, tempName, CopyOptions.None, true, CopyProgressCallback, null); if (copyResult.ErrorCode != 0) { throw new TheTVDB.TVDBException(copyResult.ErrorMessage); } } // Copying the temp file into the correct name is very quick, so no progress reporting File.Move(tempName, To.FullName, MoveOptions.ReplaceExisting); LOGGER.Info($"{Name} completed: {From.FullName} to {To.FullName } "); UpdateStats(stats); if (To.IsMovieFile()) { //File is correct name LOGGER.Debug($"Just copied {To.FullName} to the right place. Marking it as 'seen'."); //Record this episode as seen TVSettings.Instance.PreviouslySeenEpisodes.EnsureAdded(Episode); if (TVSettings.Instance.IgnorePreviouslySeen) { doc.SetDirty(); } } } catch (Exception e) { LOGGER.Warn(e, $"Error occurred while {Name}: {From.FullName} to {To.FullName } "); return(new ActionOutcome(e)); } // set NTFS permissions try { if (security != null) { To.SetAccessControl(security); } } catch { // ignored } try { if (Operation == Op.move && Tidyup != null && Tidyup.DeleteEmpty) { LOGGER.Info($"Testing {From.Directory.FullName} to see whether it should be tidied up"); DoTidyup(From.Directory); } } catch (Exception e) { return(new ActionOutcome(e)); } return(ActionOutcome.Success()); }
public void SetAccessControl(FileSecurity fileSecurity) { File.SetAccessControl(FullPath, fileSecurity); }
public void SetAccessControl(string path, FileSecurity fileSecurity) { File.SetAccessControl(path, fileSecurity); }
/// <summary> /// Initializes a new instance of the <see cref="T:UnitWrappers.System.IO.FileStreamWrap"/> class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security. /// </summary> /// <param name="path">A relative or absolute path for the file that the current FileStream object will encapsulate.</param> /// <param name="mode">A FileMode constant that determines how to open or create the file.</param> /// <param name="rights">A FileSystemRights constant that determines the access rights to use when creating access and audit rules for the file.</param> /// <param name="share">A FileShare constant that determines how the file will be shared by processes. </param> /// <param name="bufferSize">A positive Int32 value greater than 0 indicating the buffer size. For bufferSize values between one and eight, the actual buffer size is set to eight bytes.</param> /// <param name="options">A FileOptions value that specifies additional file options.</param> /// <param name="fileSecurity">A FileSecurity constant that determines the access control and audit security for the file.</param> public FileStreamWrap(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity) { _underlyingObject = new FileStream(path, mode, rights, share, bufferSize, options, fileSecurity); }
/// <summary> /// Loads the constants from the application database /// </summary> private void LoadConstants() { // Load the shared users program settings. string[] pathSegments = new string[] { Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "EDESuite", $"TEST", this.GetAssemblyDescription(), }; this.ApplicationConfigFolder = Path.Combine(pathSegments); this.applicationSettingsFile = Path.Combine(this.ApplicationConfigFolder, "EDESuite.xml"); XmlDocument doc = new XmlDocument(); if (File.Exists(this.applicationSettingsFile)) { doc.Load(this.applicationSettingsFile); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("x", doc.DocumentElement.NamespaceURI); XmlNode n = doc.DocumentElement.SelectSingleNode("x:Database", nsmgr); if (n != null) { //this.SchoolDatabaseFile = n.Attributes["Path"].Value; } n = doc.DocumentElement.SelectSingleNode("x:Executable", nsmgr); if (n != null) { this.ExecutablePath = n.Attributes["Path"].Value; } foreach (XmlNode n2 in doc.DocumentElement.SelectNodes("x:InstalledModules/x:Module[@Load='true']", nsmgr)) { this.ModulesToBeLoaded.Add(n2.Attributes["Name"].Value); } } else { if (!Directory.Exists(Path.GetDirectoryName(this.applicationSettingsFile))) { Directory.CreateDirectory(Path.GetDirectoryName(this.applicationSettingsFile)); } // Generate a new file XmlWriterSettings settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Document; settings.Indent = true; settings.NewLineHandling = NewLineHandling.Entitize; settings.NewLineOnAttributes = false; using (XmlWriter writer = XmlWriter.Create(this.applicationSettingsFile, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("EDESuite", "http://tempuri.org/EDESuiteAppSettings.xsd"); writer.WriteStartElement("Executable"); writer.WriteAttributeString("Path", Path.GetDirectoryName(typeof(AppConstants).Assembly.Location)); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); } try { // Set the file security settings so all users can modify the file. FileSecurity fileSecurity = File.GetAccessControl(this.applicationSettingsFile); foreach (FileSystemAccessRule r in fileSecurity.GetAccessRules(false, true, typeof(System.Security.Principal.NTAccount))) { if (string.Compare(r.IdentityReference.Value, "BUILTIN\\Users", true) == 0) { fileSecurity.RemoveAccessRule(r); } } FileSystemAccessRule accessRule = new FileSystemAccessRule("BUILTIN\\Users", FileSystemRights.FullControl, AccessControlType.Allow); fileSecurity.AddAccessRule(accessRule); File.SetAccessControl(this.applicationSettingsFile, fileSecurity); } catch (Exception ex) { AppObjects.Log.LogException(ex); this.settings = null; } } }
/// <summary> /// Corrects the template path in a specific word document /// </summary> /// <param name="file">path to document in filesystem</param> /// <param name="oldPath">old path to template in document</param> /// <param name="newPath">new path to template in document</param> /// <param name="makeBackup">create backup file for every corrected document</param> /// <param name="dryRun">if true the original file will not be changed</param> /// <returns>file is changed or affected</returns> static bool correctDocument(string file, string oldPath, string newPath, bool noBackup, bool dryRun, bool verbose, bool preserve) { ConsoleColor fgColor = Console.ForegroundColor; bool changed = false; string tempUnzipDir = tempDir + Path.GetFileName(file); string TargetPattern = @".*Target=""file:\/\/\/(.*?)"""; Match m; // unzip try { // Get dates DateTime dtLAT = File.GetLastAccessTimeUtc(file); DateTime dtLWT = File.GetLastWriteTimeUtc(file); DateTime dtCT = File.GetCreationTimeUtc(file); FileAttributes fAttr = File.GetAttributes(file); FileSecurity fACL = File.GetAccessControl(file); // unzip document to temp folder ZipFile.ExtractToDirectory(file, tempUnzipDir); string settingsFilePath = tempUnzipDir + @"\word\_rels\settings.xml.rels"; if (File.Exists(settingsFilePath)) { string oldContent = File.ReadAllText(settingsFilePath); // Show found target in verbose mode if (verbose) { m = Regex.Match(oldContent, TargetPattern); if (m.Success) { Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(" - Target: " + m.Groups[1]); Console.ForegroundColor = fgColor; } } string newContent = oldContent.Replace(oldPath, newPath); // replace // something changed? if (oldContent != newContent) { // check for DryRun if (dryRun) { changed = true; } else { File.WriteAllText(settingsFilePath, newContent); changed = true; // save original file try { File.Move(file, file + ".bak"); // Re-Zip files to docx try { ZipFile.CreateFromDirectory(tempUnzipDir, file); if (preserve) { // set dates (modified last operation) File.SetCreationTimeUtc(file, dtCT); File.SetLastAccessTimeUtc(file, dtLAT); File.SetAttributes(file, fAttr); File.SetAccessControl(file, fACL); File.SetLastWriteTimeUtc(file, dtLWT); } // delete backup file if wanted if (noBackup) { File.Delete(file + ".bak"); } } catch (Exception e2) { // undo rename try { File.Move(file + ".bak", file); } catch (Exception e4) { WTCException wtcEx4 = new WTCException("failed to remove backup file", e4); throw wtcEx4; } WTCException wtcEx2 = new WTCException("failed to rezip", e2); throw wtcEx2; } } catch (Exception e3) { WTCException wtcEx3 = new WTCException("failed to create backup file", e3); throw wtcEx3; } } } } // remove unzipped files and temp folder try { Directory.Delete(tempUnzipDir, true); } catch (Exception e5) { WTCException wtcEx5 = new WTCException("failed to remove temporary unzip directory", e5); throw wtcEx5; } } catch (Exception e1) { System.Console.WriteLine(e1.Message); WTCException wtcEx1 = new WTCException("failed to unzip document", e1); throw wtcEx1; } return(changed); }
public void RemoveAccessRuleSpecific_Invalid_FileSystemAccessRule() { var fileSecurity = new FileSecurity(); AssertExtensions.Throws <ArgumentNullException>("rule", () => fileSecurity.RemoveAccessRuleSpecific(null)); }
public void SetAccessRule_InvalidFileSystemAccessRule() { var fileSecurity = new FileSecurity(); AssertExtensions.Throws <ArgumentNullException>("rule", () => fileSecurity.SetAccessRule(null)); }
private void CommitWriteTransaction() { if (g_bExtraSafe) { if (!IOConnection.FileExists(m_iocTemp)) { throw new FileNotFoundException(m_iocTemp.Path + MessageService.NewLine + KLRes.FileSaveFailed); } } bool bMadeUnhidden = UrlUtil.UnhideFile(m_iocBase.Path); #if !KeePassUAP // 'All' includes 'Audit' (SACL), which requires SeSecurityPrivilege, // which we usually don't have and therefore get an exception; // trying to set 'Owner' or 'Group' can result in an // UnauthorizedAccessException; thus we restore 'Access' (DACL) only const AccessControlSections acs = AccessControlSections.Access; bool bEfsEncrypted = false; byte[] pbSec = null; #endif DateTime? otCreation = null; SimpleStat sStat = null; bool bBaseExists = IOConnection.FileExists(m_iocBase); if (bBaseExists && m_iocBase.IsLocalFile()) { // FileAttributes faBase = FileAttributes.Normal; try { #if !KeePassUAP FileAttributes faBase = File.GetAttributes(m_iocBase.Path); bEfsEncrypted = ((long)(faBase & FileAttributes.Encrypted) != 0); try { if (bEfsEncrypted) { File.Decrypt(m_iocBase.Path); } } // For TxF catch (Exception) { Debug.Assert(false); } #endif otCreation = File.GetCreationTimeUtc(m_iocBase.Path); sStat = SimpleStat.Get(m_iocBase.Path); #if !KeePassUAP // May throw with Mono FileSecurity sec = File.GetAccessControl(m_iocBase.Path, acs); if (sec != null) { pbSec = sec.GetSecurityDescriptorBinaryForm(); } #endif } catch (Exception) { Debug.Assert(NativeLib.IsUnix()); } // if((long)(faBase & FileAttributes.ReadOnly) != 0) // throw new UnauthorizedAccessException(); } if (!TxfMove()) { if (bBaseExists) { IOConnection.DeleteFile(m_iocBase); } IOConnection.RenameFile(m_iocTemp, m_iocBase); } else { Debug.Assert(pbSec != null); } // TxF success => NTFS => has ACL try { // If File.GetCreationTimeUtc fails, it may return a // date with year 1601, and Unix times start in 1970, // so testing for 1971 should ensure validity; // https://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc.aspx if (otCreation.HasValue && (otCreation.Value.Year >= 1971)) { File.SetCreationTimeUtc(m_iocBase.Path, otCreation.Value); } if (sStat != null) { SimpleStat.Set(m_iocBase.Path, sStat); } #if !KeePassUAP if (bEfsEncrypted) { try { File.Encrypt(m_iocBase.Path); } catch (Exception) { Debug.Assert(false); } } // File.SetAccessControl(m_iocBase.Path, secPrev); // Directly calling File.SetAccessControl with the previous // FileSecurity object does not work; the binary form // indirection is required; // https://sourceforge.net/p/keepass/bugs/1738/ // https://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol.aspx if ((pbSec != null) && (pbSec.Length != 0)) { FileSecurity sec = new FileSecurity(); sec.SetSecurityDescriptorBinaryForm(pbSec, acs); File.SetAccessControl(m_iocBase.Path, sec); } #endif } catch (Exception) { Debug.Assert(false); } if (bMadeUnhidden) { UrlUtil.HideFile(m_iocBase.Path, true); } }
/// <summary> /// Set the permission on a file for the target User. /// </summary> /// <param name="fileId"></param> /// <param name="user"></param> /// <param name="targetUser"></param> /// <param name="canRead"></param> /// <param name="canWrite"></param> /// <param name="canDelete"></param> /// <param name="context"></param> /// <param name="dbcxtransaction"></param> public static void SetPermissions(Guid fileId, Principal user, Principal targetUser, bool canRead, bool canWrite, bool canDelete, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null) { bool createdContext = false; bool createdTransaction = false; bool didRollback = false; if (context == null) { createdContext = true; context = new OnlineFilesEntities(); } if (dbcxtransaction == null) { dbcxtransaction = context.Database.BeginTransaction(); createdTransaction = true; } try { File targetfile = context.Files .Include(d => d.FileSecurities) .FirstOrDefault(d => d.pk_FileId == fileId); if (targetfile == null) throw new Exception("File does not exist."); Folder target = context.Folders.Include(d => d.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == targetfile.fk_FolderId); if (target == null) throw new Exception("Parent Folder does not exist."); //Can the user Change Permissions if (target.FolderSecurities.Any(d => d.canChangePermissions && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId))) { var secRecord = targetfile.FileSecurities.FirstOrDefault(d => d.SecurityObjectId == targetUser.UserProfile.SecurityObjectId); if (secRecord == null) { secRecord = new FileSecurity { fk_FileId = targetfile.pk_FileId, CanDelete = canDelete, canRead = canRead, canWrite = canWrite, SecurityObjectId = targetUser.UserProfile.SecurityObjectId }; targetfile.FileSecurities.Add(secRecord); } else { secRecord.canRead = canRead; secRecord.CanDelete = canDelete; secRecord.canWrite = canWrite; } context.SaveChanges(); } else { throw new SecurityException("Not Authorized."); } } catch (Exception) { if (!createdTransaction) throw; didRollback = true; dbcxtransaction.Rollback(); throw; } finally { if (createdTransaction) { if (!didRollback) dbcxtransaction.Commit(); dbcxtransaction.Dispose(); } if (createdContext) context.Dispose(); } }
public override Stream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { return(File.Create(path, bufferSize, options, fileSecurity)); }
public static void SetAccessControl(FileStream fileStream, FileSecurity fileSecurity);
public FileStream(String path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity) { Object pinningHandle; Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share, fileSecurity, out pinningHandle); try { Init(path, mode, (FileAccess)0, (int)rights, true, share, bufferSize, options, secAttrs, Path.GetFileName(path), false, false); } finally { if (pinningHandle != null) { GCHandle pinHandle = (GCHandle) pinningHandle; pinHandle.Free(); } } }