public string GetOwner(FileSystemInfo info) { string owner = string.Empty; try { if (info is DirectoryInfo) { DirectorySecurity security = Directory.GetAccessControl(info.FullName); owner = security.GetOwner(typeof(NTAccount)).ToString(); } else // if (info is FileInfo) { FileSecurity security = File.GetAccessControl(info.FullName); owner = security.GetOwner(typeof(NTAccount)).ToString(); } var principal = Helpers.FindByIdentity(owner); if (principal != null) { string name = principal.DisplayName; if (!string.IsNullOrEmpty(name)) { owner += $" ({name})"; } } } catch { } return(owner); }
public void GetOwnershipTest2() { // Arrange var tmpDir = Path.Combine(Path.GetTempPath(), "dirtools-test-" + Guid.NewGuid().ToString()); Directory.CreateDirectory(tmpDir); var tmpFile = Path.Combine(tmpDir, "asdf"); var localSystem = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); var fileSec = new FileSecurity(); fileSec.SetOwner(localSystem); File.Create(tmpFile, 1, FileOptions.None, fileSec).Dispose(); // Act var curIdentity = new NTAccount(Environment.UserDomainName, Environment.UserName); DirectoryTools.GetOwnershipForDirectory(tmpFile, curIdentity); // Assert var curFilesec = new FileSecurity(tmpFile, AccessControlSections.Owner); IdentityReference owner = curFilesec.GetOwner(typeof(NTAccount)); Assert.IsTrue(curIdentity == owner); }
/// <summary> /// Dosyanın sahibi olan kullanıcıyı verir.</summary> /// <summary> /// Returns the file owner</summary> /// <param name="fileName"> /// Filename.</param> /// <returns> /// Full username like DOMAIN\NAME</returns> public static string FileOwnerName(string fileName) { FileSecurity sec = new FileSecurity(fileName, AccessControlSections.Owner); IdentityReference id = sec.GetOwner(typeof(NTAccount)); return(id.Value); }
/// <summary> /// Check writing access to path /// </summary> static public bool CheckWriteAccess(string path) { bool result = true; try { FileSecurity security = File.GetAccessControl(path, AccessControlSections.Access | AccessControlSections.Owner); NTAccount owner = (NTAccount)security.GetOwner(typeof(NTAccount)); foreach (FileSystemAccessRule rule in security.GetAccessRules(true, true, typeof(NTAccount))) { if (rule.AccessControlType != AccessControlType.Allow) { result = false; break; // NOTE: all must Allow - first breakdown - exit } } } catch { result = false; } return(result); }
/// <summary> /// Populates the block with the initial files. /// </summary> /// <returns>Return the blockchain</returns> public static Blockchain PopulateBlockchain() { Functions functions = new Functions(); string path; string date = DateTime.Now.ToString().Replace(':', '-').Trim(); List <string> filesPaths = Directory.GetFiles(GlobalVariables.FolderToWatch).ToList(); filesPaths.RemoveAll(f => f.Contains("~$")); Blockchain files = new Blockchain(); for (int i = 0; i < filesPaths.Count; i++) { FileInfo f = new FileInfo(filesPaths[i]); FileSecurity fS = f.GetAccessControl(); Block block = new Block(DateTime.Now, "") { FileExtension = f.Extension, FileName = f.Name, FullPath = f.FullName, CreatedDate = f.CreationTime, LastEdited = System.IO.File.GetLastWriteTime(filesPaths[i]), LastEditedForCheck = System.IO.File.GetLastWriteTime(filesPaths[i]), LastEditedBy = fS.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(), FileNameForList = f.Name }; path = functions.CopyFiles(block.FileName + date, block.FileExtension, block.FullPath); block.FullPath = path; files.AddBlock(block); } return(files); }
private static string GetFileOwnerName(string path) { FileSecurity fileSecurity = File.GetAccessControl(path); IdentityReference identityReference = fileSecurity.GetOwner(typeof(SecurityIdentifier)); NTAccount ntAccount = identityReference.Translate(typeof(NTAccount)) as NTAccount; return(ntAccount.Value); }
public string GetOwnerName(string path) { //string user = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(); FileSecurity fileSecurity = File.GetAccessControl(path); IdentityReference identityReference = fileSecurity.GetOwner(typeof(SecurityIdentifier)); NTAccount ntAccount = identityReference.Translate(typeof(NTAccount)) as NTAccount; return(ntAccount.Value); }
/// <summary> /// Retrieves a particular principal as being the "owner" of the item. /// </summary> /// <remarks>Required by OS X.</remarks> /// <returns> /// Item that represents owner of this item and implements <see cref="IPrincipalAsync"/>. /// </returns> public async Task <IPrincipalAsync> GetOwnerAsync() { return(context.FileOperation( this, () => { FileSecurity acl = File.GetAccessControl(fileSystemInfo.FullName); return AclFactory.GetPrincipalFromSid(acl.GetOwner(typeof(SecurityIdentifier)).Value, context); }, Privilege.Read)); }
private long GetWOwner() { // <TODO> !!! Type obTypeToGet = Type.GetType("System.Security.Principal.NTAccount"); //return File.GetAccessControl(originalFileName).GetOwner(obTypeToGet).ToString FileInfo fileInfo = new FileInfo(@"C:\Contacts.txt"); FileSecurity fileSecurity = fileInfo.GetAccessControl(); IdentityReference identityReference = fileSecurity.GetOwner(typeof(NTAccount)); return(0); }
public static string GetOwner(this IFileSystemInfo systemInfo) { try { FileSecurity security = GetFileSecurity(systemInfo); return(security.GetOwner(typeof(NTAccount)).Value); } catch (UnauthorizedAccessException) { return("Unknown"); } }
/// <summary> /// Access, Owner, Inheritedの情報を読み込み /// </summary> public void LoadSecurity() { FileSecurity security = File.GetAccessControl(_Path); // Access this.Access = FileControl.AccessRulesToString(security.GetAccessRules(true, false, typeof(NTAccount))); // Owner this.Owner = security.GetOwner(typeof(NTAccount)).Value; // Inherited this.Inherited = !security.AreAccessRulesProtected; }
public static string GetFileBelongs(FileInfo fileInfo) { try { FileSecurity fileSecurity = fileInfo.GetAccessControl(); IdentityReference identityReference = fileSecurity.GetOwner(typeof(NTAccount)); return(identityReference.Value); } catch (Exception ex) { return("<UnKnow>"); } }
public static string GetRightsListing(this IFileSystemInfo systemInfo) { var builder = new StringBuilder(); builder.Append((char)GetDirectoryIndication(systemInfo)); try { FileSecurity security = GetFileSecurity(systemInfo); var owner = security.GetOwner(typeof(NTAccount)); if (owner == null) { } var ownerRights = new Rights(); var group = security.GetGroup(typeof(NTAccount)); var groupRights = new Rights(); var others = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null).Translate(typeof(NTAccount)); var othersRights = new Rights(); var authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount)); //security.ModifyAccessRule(AccessControlModification.Add, // new FileSystemAccessRule(owner, FileSystemRights.Modify, AccessControlType.Allow), // out bool modified); foreach (AuthorizationRule rule in authorizationRules) { FileSystemAccessRule fileRule = rule as FileSystemAccessRule; if (fileRule != null) { if (owner != null && fileRule.IdentityReference == owner) { ReadRights(fileRule, ownerRights); } else if (group != null && fileRule.IdentityReference == group) { ReadRights(fileRule, groupRights); } if (fileRule.IdentityReference == others) { ReadRights(fileRule, othersRights); } } } builder.Append(ownerRights); builder.Append(groupRights); builder.Append(othersRights); } catch (Exception) { // Silently hide exception builder.Append("---------"); } return(builder.ToString()); }
public static void ModifyFileOwner(string file, string owner) { try { Console.WriteLine("~~~~~~~~~~~~~ModifyFileOwner~~~~~~~~~~~~~~~~~~~~"); FileInfo fi = new FileInfo(file); ///////////////////////////////////////////////////////////// FileSecurity fssec = fi.GetAccessControl(); SecurityIdentifier sid = fssec.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier; NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount; Console.WriteLine($"Original owner sid is '{sid}', user account is '{account}' of file '{file}'"); ///////////////////////////////////////////////////////////// NTAccount current = WindowsIdentity.GetCurrent().User.Translate(typeof(NTAccount)) as NTAccount; NTAccount newOwner = string.IsNullOrEmpty(owner) ? current : new NTAccount(owner); SecurityIdentifier newSidOwner = newOwner.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier; Console.WriteLine($"Trying to set new owner sid is '{newSidOwner}', user account is '{newOwner}' of file '{file}'"); ///////////////////////////////////////////////////////////// fssec.SetOwner(newOwner); fi.SetAccessControl(fssec); /////////////////////////////////////////////////////////// fssec = fi.GetAccessControl(); sid = fssec.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier; account = sid.Translate(typeof(NTAccount)) as NTAccount; Console.WriteLine($"New owner sid is '{sid}', user account is '{account}' of file '{file}'"); } catch (Exception ex) { Console.WriteLine($"failed to ModifyFileOwner for {file} with error {ex.Message} "); //throw; } }
private static void ExtractFileInfo(Autorunpoints runPoint) { bool isFileExist = false; if (string.IsNullOrEmpty(runPoint.FilePath)) { return; } IntPtr wow64Value = IntPtr.Zero; if (File.Exists(runPoint.FilePath)) { isFileExist = true; } else { if (runPoint.FilePath.ToLower().StartsWith(@"c:\windows\system32")) { Forensics.Util.Wow64DisableWow64FsRedirection(ref wow64Value); if (File.Exists(runPoint.FilePath)) { isFileExist = true; } } } if (isFileExist) { try { FileInfo fi = new FileInfo(runPoint.FilePath); runPoint.FileCreated = fi.CreationTimeUtc.ToString("yyyy-MM-dd HH:mm:ss.fff"); runPoint.FileModified = fi.LastWriteTimeUtc.ToString("yyyy-MM-dd HH:mm:ss.fff"); FileSecurity fileSecurity = File.GetAccessControl(runPoint.FilePath); IdentityReference sid = fileSecurity.GetOwner(typeof(SecurityIdentifier)); NTAccount ntAccount = sid.Translate(typeof(NTAccount)) as NTAccount; runPoint.FileOwner = ntAccount.Value; } catch (Exception) { } } if (wow64Value != IntPtr.Zero) { Forensics.Util.Wow64RevertWow64FsRedirection(wow64Value); } }
public int RunInfoAndReturnExitCode() { var config = new AllSettings(); if (Utils.TestConfigtation()) { if (Utils.IsAnyPendigFile()) { string rootPath = config.WorkingDirectory; string[] dirs = Directory.GetDirectories(rootPath); foreach (var folder in dirs) { string[] files = Directory.GetFiles(folder, "*.sql", SearchOption.AllDirectories); Console.WriteLine(""); var table = new ConsoleTable("Group", "File Name", "State", "Owner"); foreach (string file in files) { string filename = Path.GetFileNameWithoutExtension(file); FileInfo fileInfo = new FileInfo(file); FileSecurity fileSecurity = fileInfo.GetAccessControl(); IdentityReference identityReference = fileSecurity.GetOwner(typeof(NTAccount)); var directoryInfo = new DirectoryInfo(file).Parent; if (directoryInfo != null) { string result = directoryInfo.Name; table.AddRow(result, filename, "pending", identityReference.Value); } } table.Write(); } } else { Console.WriteLine(string.Concat("Pending file not found in working directory: ", config.WorkingDirectory)); } } else { Console.WriteLine("Configration is missing..."); Utils.DisplayConfigration(); } return(0); }
public void FileOwner() { string tempFile = Path.GetTempFileName(); FileInfo fi = new FileInfo(tempFile); FileSecurity fs = fi.GetAccessControl(AccessControlSections.Owner); string expected = fs.GetOwner(typeof(NTAccount)).ToString(); ExtendedFileInfo efi = new ExtendedFileInfo(tempFile); Assert.IsNotNull(efi); string actual = efi.FileOwner; Assert.AreEqual(expected, actual); }
public void File_Info(string str_file) ////// файл_инфо { name.Content = "Name:"; date.Content = "Date:"; autor.Content = "Author:"; FileInfo fin = new FileInfo(str_file); name.Content = name.Content + " " + fin.Name; date.Content = date.Content + " " + fin.LastWriteTime.ToShortDateString(); FileSecurity fileSecurity = fin.GetAccessControl(); //// get author))) IdentityReference identityReference = fileSecurity.GetOwner(typeof(NTAccount)); autor.Content = autor.Content + " " + identityReference.Value; }
private static string GetAuthorFromOtherFileType(string path) { var security = new FileSecurity(path, AccessControlSections.Owner | AccessControlSections.Group | AccessControlSections.Access); var owner = security.GetOwner(typeof(NTAccount)).ToString(); if (owner.Contains(@"\")) { owner = owner.Split(@"\")[1]; } return(owner.Substring(0, 1).ToUpper() + owner.Substring(1).ToLower()); }
private static void Info(VuberConfig config) { if (Utils.TestConfigtation()) { if (Utils.IsAnyPendigFile()) { string rootPath = config.WorkingDirectory; string[] dirs = Directory.GetDirectories(rootPath); foreach (var folder in dirs) { string[] files = Directory.GetFiles(folder, "*.sql", SearchOption.AllDirectories); var table = new ConsoleTable("Group", "File Name", "State", "Owner"); foreach (string file in files) { string filename = Path.GetFileNameWithoutExtension(file); FileInfo fileInfo = new FileInfo(file); FileSecurity fileSecurity = fileInfo.GetAccessControl(); IdentityReference identityReference = fileSecurity.GetOwner(typeof(NTAccount)); var directoryInfo = new DirectoryInfo(file).Parent; if (directoryInfo != null) { string result = directoryInfo.Name; table.AddRow(result, filename, "pending", identityReference.Value); } } table.Write(); } } else { Console.WriteLine("No Pending File"); } } else { Console.WriteLine("Configration is missing..."); Utils.DisplayConfigration(); } }
public static string GetFileOwner(string file) { string owner = "not found"; try { FileSecurity fileSecurity = new FileSecurity(file, AccessControlSections.Owner); IdentityReference identityReference = fileSecurity.GetOwner(typeof(SecurityIdentifier)); owner = identityReference.Value; NTAccount nt = identityReference.Translate(typeof(NTAccount)) as NTAccount; owner = nt.Value; } catch { } return(owner); }
/// <summary> /// Replaces the permissions of the file at the given <paramref name="targetPath"/> /// with the inheritable permissions from the directory at the given <paramref name="sourcePath"/>. /// </summary> /// <param name="sourcePath">The path to the directory from which to derive inheritable permissions.</param> /// <param name="targetPath">The path to the file to which to apply the derived permissions.</param> public static void ApplyInheritableFilePermissions(string sourcePath, string targetPath) { string sourceAbsolutePath = GetAbsolutePath(sourcePath); string targetAbsolutePath = GetAbsolutePath(targetPath); DirectorySecurity sourceSecurity = Directory.GetAccessControl(sourceAbsolutePath); FileSecurity targetSecurity = File.GetAccessControl(targetAbsolutePath); IdentityReference targetOwner = targetSecurity.GetOwner(typeof(NTAccount)); IdentityReference targetGroup = targetSecurity.GetGroup(typeof(NTAccount)); targetSecurity = new FileSecurity(); // This prevents permissions modifications by the target file's parents (the target's inherited permissions) targetSecurity.SetAccessRuleProtection(true, false); foreach (FileSystemAccessRule rule in sourceSecurity.GetAccessRules(true, true, typeof(NTAccount))) { // If the inheritance flags indicate that this rule // is not inheritable by subfolders, skip it if (!rule.InheritanceFlags.HasFlag(InheritanceFlags.ObjectInherit)) { continue; } IdentityReference identityReference = rule.IdentityReference; FileSystemRights fileSystemRights = rule.FileSystemRights; AccessControlType accessControlType = rule.AccessControlType; // If the rule is associated with the CREATOR OWNER identity or the CREATOR GROUP identity, // the new rule must instead be associated with the actual owner or group of the target file if (identityReference.Value == "CREATOR OWNER") { identityReference = targetOwner; } else if (identityReference.Value == "CREATOR GROUP") { identityReference = targetGroup; } targetSecurity.AddAccessRule(new FileSystemAccessRule(identityReference, fileSystemRights, accessControlType)); } File.SetAccessControl(targetAbsolutePath, targetSecurity); }
void Init(FileSystemInfo fsi) { Path = fsi.FullName; Name = fsi.Name; CreateTime = fsi.CreationTime; LastModTime = fsi.LastWriteTime; Permissions = GetPermissions(fsi.Attributes); Source = SourceType.Local; try { FileSecurity fs = File.GetAccessControl(fsi.FullName); Owner = fs.GetOwner(typeof(NTAccount)).ToString(); Group = fs.GetGroup(typeof(NTAccount)).ToString(); } catch (Exception ex) { Log.DebugFormat("Unable to get owner/group. dir={0}, err={1}", fsi.FullName, ex.Message); } }
//public static bool ValidateFilePath(string filePath) //{ // Regex r = new Regex( @"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$" ); // return r.IsMatch(filePath); //} static public bool CheckWriteAccess(string path) { bool result = true; FileSecurity security = File.GetAccessControl(path, AccessControlSections.Access | AccessControlSections.Owner); NTAccount owner = (NTAccount)security.GetOwner(typeof(NTAccount)); Console.WriteLine("Owner: {0}", owner.Value); // DACLs foreach (FileSystemAccessRule rule in security.GetAccessRules(true, true, typeof(NTAccount))) { Console.WriteLine("{0} {1} access to {2}", rule.AccessControlType == AccessControlType.Allow ? "grant: " : "deny: ", rule.FileSystemRights, rule.IdentityReference.ToString()); } return(result); }
static void ChangeOwner(FileInfo fileInfo, System.Security.Principal.IdentityReference currentOwnerId, System.Security.Principal.IdentityReference newOwnerId) { CheckAttributes(fileInfo); try { FileSecurity fileSec = fileInfo.GetAccessControl(); if (fileSec.GetOwner(typeof(System.Security.Principal.SecurityIdentifier)) == currentOwnerId) { ++sNumChanged; if (!sDryRun) { fileSec.SetOwner(newOwnerId); fileInfo.SetAccessControl(fileSec); } Console.WriteLine("Set ownership on file '{0}' to '{1}'", fileInfo.FullName, newOwnerId.ToString()); } } catch (ArgumentException) { Console.WriteLine("Weird exception processing file '{0}'", fileInfo.FullName); } catch (Exception exception) { Console.WriteLine("Exception processing file '{0}': '{1}'", fileInfo.FullName, exception.Message); } }
/// <summary> /// Initializes a new instance of the <see cref="ExtendedFileInfo"/> /// class that wraps an instance of <see cref="IFileInfo"/>. /// </summary> /// <param name="fileInfo"> /// The <see cref="IFileInfo"/> representing the file. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="fileInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="SecurityException"> /// The caller does not have the required permission. /// </exception> /// <exception cref="ArgumentException"> /// The file name is empty, contains only white spaces, or contains /// invalid characters. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// Access to <paramref name="fileInfo"/> is denied. /// </exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined /// maximum length. For example, on Windows-based platforms, paths must /// be less than 248 characters, and file names must be less than 260 characters. /// </exception> /// <exception cref="NotSupportedException"> /// <paramref name="fileInfo"/> contains a colon (:) in the middle of /// the string. /// </exception> /// <remarks> /// You can specify either the fully qualified or the relative file /// name, but the security check gets the fully qualified name. /// </remarks> public ExtendedFileInfo(IFileInfo fileInfo) { var fileName = fileInfo.PhysicalPath; this.originalFileName = fileName; this.fileInfo = new FileInfo(fileName); if (this.fileInfo.Exists) { this.fileVersionInfo = FileVersionInfo.GetVersionInfo(fileName); #if NET5_0 if (OperatingSystem.IsWindows()) { var fs = new FileSecurity(this.originalFileName, AccessControlSections.Owner); this.FileOwner = fs.GetOwner(typeof(NTAccount))?.ToString(); } #else var fs = new FileSecurity(this.originalFileName, AccessControlSections.Owner); this.FileOwner = fs.GetOwner(typeof(NTAccount))?.ToString(); #endif } }
public void Button1_Click(object sender, EventArgs e) { Path_file = textBox1.Text; try { FileInfo fileInfo = new FileInfo(Path_file); FileSecurity fileSecurity = fileInfo.GetAccessControl(); IdentityReference identityReference = fileSecurity.GetOwner(typeof(NTAccount)); string acl = ""; int IntegrityLevel_File = GetFileIntegrityLevel(Path_file); string IntegrityLevel_File_str = ""; if (IntegrityLevel_File == 0) { IntegrityLevel_File_str = "Untrusted"; } else if (IntegrityLevel_File == 1) { IntegrityLevel_File_str = "Low"; } else if (IntegrityLevel_File == 2) { IntegrityLevel_File_str = "Medium"; } else if (IntegrityLevel_File == 3) { IntegrityLevel_File_str = "High"; } else { IntegrityLevel_File_str = "System"; } acl = GetDirectorySecurity(Path_file); ListView3(identityReference.Value, acl, IntegrityLevel_File_str); } catch { MessageBox.Show("Bad String"); } }
private void SetFileOwner(string path, string dn, string un, bool _lock) { IdentityReference owner = new NTAccount(dn + "\\" + un); if (!_lock) { foreach (object[] o in held) { if ((string)o[1] == path) { owner = new NTAccount((string)o[1]); break; } } } FileInfo fi = new FileInfo(path); FileSecurity fs = fi.GetAccessControl(); string x = fs.GetOwner(typeof(NTAccount)).ToString(); originalOwner = x; fs.SetOwner(owner); fi.SetAccessControl(fs); }
private static void OwnthatFile(string filename) { // Way safer than string comparison against "BUILTIN\\Administrators" IdentityReference BuiltinAdministrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); // Grab ACL from file FileSecurity FileACL = File.GetAccessControl(filename); // Check if correct owner is set if (FileACL.GetOwner(typeof(SecurityIdentifier)) != BuiltinAdministrators) { // If not, make it so! FileACL.SetOwner(BuiltinAdministrators); } foreach (FileSystemAccessRule fsRule in FileACL.GetAccessRules(true, false, typeof(SecurityIdentifier))) { // Check if rule grants delete if ((fsRule.FileSystemRights & FileSystemRights.Write) == FileSystemRights.Write) { // If so, nuke it! FileACL.RemoveAccessRule(fsRule); } } // Add a single explicit rule to allow FullControl FileACL.AddAccessRule(new FileSystemAccessRule(BuiltinAdministrators, FileSystemRights.FullControl, AccessControlType.Allow)); // Enable protection from inheritance, remove existing inherited rules FileACL.SetAccessRuleProtection(true, false); // Write ACL back to file File.SetAccessControl(filename, FileACL); }
/// <summary> /// Populates the list with the files to check. /// </summary> /// <returns>Return the list</returns> public List <FileModel> PopulateFilesList() { List <string> filesPaths = Directory.GetFiles(GlobalVariables.FolderToWatch).ToList(); List <FileModel> files = new List <FileModel>(); for (int i = 0; i < filesPaths.Count; i++) { FileInfo f = new FileInfo(filesPaths[i]); FileSecurity fS = f.GetAccessControl(); files.Add(new FileModel() { FileExtension = f.Extension, FileName = f.Name, FullPath = f.FullName, CreatedDate = f.CreationTime, LastEdited = System.IO.File.GetLastWriteTime(filesPaths[i]), LastEditedForCheck = System.IO.File.GetLastWriteTime(filesPaths[i]), LastEditedBy = fS.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(), hasThread = false }); } return(files); }