public static void ModifyDirOwner(string dir, string owner) { try { Console.WriteLine("*****************ModifyDirOwner*****************************"); DirectoryInfo di = new DirectoryInfo(dir); ///////////////////////////////////////////////////////////// DirectorySecurity dirsec = null; try { dirsec = di.GetAccessControl(); } catch (Exception ex1) { Console.WriteLine($"failed to GetAccessControl for {dir} with error {ex1.Message}, try its parent {di.Parent} "); dirsec = di.Parent.GetAccessControl(); } SecurityIdentifier sid = dirsec.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 directory '{dir}'"); ///////////////////////////////////////////////////////////// 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 directory '{dir}'"); ///////////////////////////////////////////////////////////// dirsec.SetOwner(newOwner); di.SetAccessControl(dirsec); /////////////////////////////////////////////////////////// dirsec = di.GetAccessControl(); sid = dirsec.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier; account = sid.Translate(typeof(NTAccount)) as NTAccount; Console.WriteLine($"New owner sid is '{sid}', user account is '{account}' of directory '{dir}'"); } catch (Exception ex) { Console.WriteLine($"failed to ModifyDirOwner for {dir} with error {ex.Message} "); //throw; } }
static void ChangeOwner(DirectoryInfo dirInfo, System.Security.Principal.IdentityReference currentOwnerId, System.Security.Principal.IdentityReference newOwnerId) { CheckAttributes(dirInfo); if ((dirInfo.Attributes & FileAttributes.ReparsePoint) != 0) { // Ignore reparse points return; } try { DirectorySecurity dirSec = dirInfo.GetAccessControl(); if (dirSec.GetOwner(typeof(System.Security.Principal.SecurityIdentifier)) == currentOwnerId) { ++sNumChanged; if (!sDryRun) { dirSec.SetOwner(newOwnerId); dirInfo.SetAccessControl(dirSec); } Console.WriteLine("Set ownership on directory '{0}' to '{1}'", dirInfo.FullName, newOwnerId.ToString()); } } catch (Exception exception) { Console.WriteLine("Exception processing file '{0}': '{1}'", dirInfo.FullName, exception.Message); } }
/// <summary> /// Replaces the permissions of the directory 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 directory to which to apply the derived permissions.</param> public static void ApplyInheritableDirectoryPermissions(string sourcePath, string targetPath) { string sourceAbsolutePath = GetAbsolutePath(sourcePath); string targetAbsolutePath = GetAbsolutePath(targetPath); DirectorySecurity sourceSecurity = Directory.GetAccessControl(sourceAbsolutePath); DirectorySecurity targetSecurity = Directory.GetAccessControl(targetAbsolutePath); IdentityReference targetOwner = targetSecurity.GetOwner(typeof(NTAccount)); IdentityReference targetGroup = targetSecurity.GetGroup(typeof(NTAccount)); targetSecurity = new DirectorySecurity(); // This prevents permissions modifications by the target directory's parents (the target's inherited permissions) targetSecurity.SetAccessRuleProtection(true, false); foreach (FileSystemAccessRule rule in sourceSecurity.GetAccessRules(true, true, typeof(NTAccount))) { InheritanceFlags inheritanceFlags = rule.InheritanceFlags; // If the inheritance flags indicate that this rule // is not inheritable by subfolders, skip it if (!inheritanceFlags.HasFlag(InheritanceFlags.ContainerInherit)) { continue; } IdentityReference identityReference = rule.IdentityReference; FileSystemRights fileSystemRights = rule.FileSystemRights; AccessControlType accessControlType = rule.AccessControlType; // If the rule is associated with the CREATOR OWNER identity, add an additional rule // for the target's owner that applies only to the target directory (not inheritable) if (identityReference.Value == "CREATOR OWNER") { targetSecurity.AddAccessRule(new FileSystemAccessRule(targetOwner, fileSystemRights, accessControlType)); } // If the rule is associated with the CREATOR GROUP identity, add an additional rule // for the target's group that applies only to the target directory (not inheritable) if (identityReference.Value == "CREATOR GROUP") { targetSecurity.AddAccessRule(new FileSystemAccessRule(targetGroup, fileSystemRights, accessControlType)); } // If the rule applies only to objects within the source directory, // clear inheritance flags so it will not propagate to subfolders // and files within the target directory if (rule.PropagationFlags.HasFlag(PropagationFlags.NoPropagateInherit)) { inheritanceFlags = InheritanceFlags.None; } // Inherited permissions never inherit propagation flags PropagationFlags propagationFlags = PropagationFlags.None; targetSecurity.AddAccessRule(new FileSystemAccessRule(identityReference, fileSystemRights, inheritanceFlags, propagationFlags, accessControlType)); } Directory.SetAccessControl(targetAbsolutePath, targetSecurity); }
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); }
/// <summary> /// Access, Owner, Inheritedの情報を読み込み /// </summary> public void LoadSecurity() { DirectorySecurity security = Directory.GetAccessControl(_Path); // Access this.Access = DirectoryControl.AccessRulesToString(security.GetAccessRules(true, false, typeof(NTAccount))); // Owner this.Owner = security.GetOwner(typeof(NTAccount)).Value; // Inherited this.Inherited = !security.AreAccessRulesProtected; }
public void DirectoryOwner() { string path = Path.Combine(Path.GetTempPath(), "CadruTest"); Directory.CreateDirectory(path); DirectoryInfo di = new DirectoryInfo(path); DirectorySecurity ds = di.GetAccessControl(AccessControlSections.Owner); string expected = ds.GetOwner(typeof(NTAccount)).ToString(); ExtendedDirectoryInfo edi = new ExtendedDirectoryInfo(path); Assert.IsNotNull(edi); string actual = edi.DirectoryOwner; Assert.AreEqual(expected, actual); }
/// <summary> /// /// </summary> /// <param name="Path">Directory path</param> /// <param name="Name">Directory Name</param> /// <return>Returns owners name</return> public static String whoIsOwner(String Path, String Name) { String dir = BuildDirectory(Path, Name); String Value = null; if (IsElevated) { DirectoryInfo di = new DirectoryInfo(dir); DirectorySecurity dsec = di.GetAccessControl(AccessControlSections.Owner); IdentityReference identityReference = dsec.GetOwner(typeof(SecurityIdentifier)); NTAccount ntAccount = identityReference.Translate(typeof(NTAccount)) as NTAccount; Value = ntAccount.Value; } else { Value = "Must be run with Elevation"; } return(Value); }
public void GetOwnershipTest() { // Arrange var tmpDir = Path.Combine(Path.GetTempPath(), "dirtools-test-" + Guid.NewGuid().ToString()); var localSystem = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); var dirSec = new DirectorySecurity(); dirSec.SetOwner(localSystem); Directory.CreateDirectory(tmpDir, dirSec); // Act var curIdentity = new NTAccount(Environment.UserDomainName, Environment.UserName); DirectoryTools.GetOwnershipForDirectory(tmpDir, curIdentity); // Assert var curDirsec = new DirectorySecurity(tmpDir, AccessControlSections.Owner); IdentityReference owner = curDirsec.GetOwner(typeof(NTAccount)); Assert.IsTrue(curIdentity == owner); }
/// <summary> /// Liest den jeweiligen Ordner und rekursive alle Unterordner ab und speichert die Informationen in der Datenbank /// </summary> /// <param name="dInfo">Das DirectoryInfo Object des Ordners der verarbeitet werden soll</param> /// <param name="parentId">Die ID des übergeortneten Ordners</param> public static void GetDirectorySecurity(DirectoryInfo dInfo, int parentId) { if (dInfo == null) { return; } //baut eine SQL Verbindung auf MsSql mssql = new MsSql(); //mssql.Open(); // Der volle Pfad string _path_name = dInfo.FullName; // Die ID des übergeordneten Ordners int _parent_path_id = parentId; // Berechnet den Hash und speichert ihn string _path_hash = Helper.Hash(_path_name); // Ob der Ordner in der ersten Ebene ist oder nicht int _is_root = (_parent_path_id == -1) ? 1 : 0; // Die Ebene des Ordners int _scan_deepth = _path_name.TrimStart('\\').Split('\\').Count() - 1; //Ausgabe: Alle Pafde bis zur 3.Ebene werden ausgegeben //Index++; //if (_scan_deepth <= 5) //{ // //Console.WriteLine(_path_name); // float percent = (float)Index / (float)Count * 100f; // Console.WriteLine(percent.ToString("n2") + $" % of {Count} -- {_path_name}"); //} #region Prüfung ob schon vorhanden ist // Der SQL Befehl zum überprüfen ob der jeweilige Eintrag schon vorhanden ist string sql = $"SELECT _path_id FROM {MsSql.TBL_tmp_FS_Dirs} WHERE _path_hash = @PathHash"; SqlCommand cmd = new SqlCommand(sql, mssql.Con); // Der Hash wird als Parameter an den SQL Befehl gehängt cmd.Parameters.AddWithValue("@PathHash", _path_hash); // Öffnet die SQL Verbindung, führt die Abfrage durch und schließt die Verbindung wieder mssql.Open(); // Falls es den abgefragten Datensatz schon gibt, bekommt man in index die ID des Datensatzen, sonnst null var _path_id = cmd.ExecuteScalar(); mssql.Close(); #endregion #region Größenberechnung // Es gibt die Zeile long _size = 0; //if (_path_id != null) //{ // sql = $"SELECT _size FROM {MsSql.TBL_tmp_FS_Dirs} WHERE _path_id = @PathId"; // cmd = new SqlCommand(sql, mssql.Con); // // Der Hash wird als Parameter an den SQL Befehl gehängt // cmd.Parameters.AddWithValue("@PathId", _path_id); // // Öffnet die SQL Verbindung, führt die Abfrage durch und schließt die Verbindung wieder // mssql.Open(); // // Falls es den abgefragten Datensatz schon gibt, bekommt man in index die ID des Datensatzen, sonnst null // var size = cmd.ExecuteScalar(); // mssql.Close(); // if ((long)size == 0 || size == null) // _size = DirSize(dInfo); // else // _size = (long)size; //} //else //{ // _size = DirSize(dInfo); //} #endregion // Liest alle Unterordner in ein Array DirectoryInfo[] childs; try { childs = dInfo.GetDirectories(); } catch (Exception) { childs = new DirectoryInfo[1]; } // Liest die Infos über den Besitzer aus string _owner_sid = "0"; DirectorySecurity dSecurity = null; try { dSecurity = dInfo.GetAccessControl(); IdentityReference owner = dSecurity.GetOwner(typeof(SecurityIdentifier)); // FÜR SID _owner_sid = owner.Value; } catch (Exception) { } // Ob der Ordner Unterordner hat oder nicht int _has_children = (childs.Length > 0) ? 1 : 0; //Hash ist noch nicht vorhanden if (_path_id == null) { // Der SQL Befehl zum INSERT in die Datenbank sql = $"INSERT INTO {MsSql.TBL_tmp_FS_Dirs}(_path_name, _owner_sid, _path_hash, _parent_path_id, _is_root, _has_children, _scan_deepth, _size) " + $"OUTPUT INSERTED._path_id " + $"VALUES (@PathName, @OwnerSid, @PathHash, @ParentPathId, @IsRoot, @HasChildren, @ScanDeepth, @Size) "; cmd = new SqlCommand(sql, mssql.Con); // Hängt die Parameter an cmd.Parameters.AddWithValue("@PathName", _path_name); cmd.Parameters.AddWithValue("@OwnerSid", _owner_sid); cmd.Parameters.AddWithValue("@PathHash", _path_hash); cmd.Parameters.AddWithValue("@ParentPathId", _parent_path_id); cmd.Parameters.AddWithValue("@IsRoot", _is_root); cmd.Parameters.AddWithValue("@HasChildren", _has_children); cmd.Parameters.AddWithValue("@ScanDeepth", _scan_deepth); cmd.Parameters.AddWithValue("@Size", _size); // Öffnet die SQL Verbindung mssql.Open(); // Führt die Query aus _path_id = (int)cmd.ExecuteScalar(); //Schließt die Verbindung mssql.Close(); } // Hash ist noch nicht vorhanden else { // SQL Befehl zum Updaten des Eintrags sql = $"UPDATE {MsSql.TBL_tmp_FS_Dirs} " + $"SET _path_name = @PathName, _owner_sid = @OwnerSid, _path_hash = @PathHash, _parent_path_id = @ParentPathId, " + $"_is_root = @IsRoot, _has_children = @HasChildren, _scan_deepth = @ScanDeepth, _size = @Size " + $"WHERE _path_id = @PathId"; cmd = new SqlCommand(sql, mssql.Con); // Hängt die Parameter an cmd.Parameters.AddWithValue("@PathName", _path_name); cmd.Parameters.AddWithValue("@OwnerSid", _owner_sid); cmd.Parameters.AddWithValue("@PathHash", _path_hash); cmd.Parameters.AddWithValue("@ParentPathId", _parent_path_id); cmd.Parameters.AddWithValue("@IsRoot", _is_root); cmd.Parameters.AddWithValue("@HasChildren", _has_children); cmd.Parameters.AddWithValue("@ScanDeepth", _scan_deepth); cmd.Parameters.AddWithValue("@Size", _size); cmd.Parameters.AddWithValue("@PathId", (int)_path_id); // Öffnet die SQL Verbindung mssql.Open(); // Führt die Query aus cmd.ExecuteNonQuery(); //Schließt die Verbindung mssql.Close(); } // Ruft die ACL zum jeweiligen Ordner ab und schreib diese in die Datenbank if (dSecurity != null) { GetACEs(dSecurity, (int)_path_id); } // Geht über alle Unterordner (Kinder) und ruft die Funktion rekursiv auf foreach (DirectoryInfo child in childs) { GetDirectorySecurity(child, (int)_path_id); } }
/// <summary> /// Liest die Ordnerinfos der freigegebenen Ordner aus und speichert diese in der Datenbank /// </summary> /// <param name="share">Das Share Element der Freigabe</param> /// <param name="displayname">Der Name als die der Server angezeigt werden soll</param> internal static void GetSharesSecurity(Share share, string displayname) { if (share.NetName != "Install") { return; } DirectoryInfo dInfo = new DirectoryInfo(share.ToString()); if (dInfo == null) { return; } //baut eine SQL Verbindung auf MsSql mssql = new MsSql(); mssql.Open(); // Der volle Pfad (UNC Pfad) string _unc_path_name = dInfo.FullName; // Der Pfad auf dem lokalen System (z.b: x:\\Install string _path_name = share.Path; // Berechnet den Hash und speichert ihn string _path_hash = Helper.Hash(_unc_path_name); // Der Name der in ARPS angezeigt werden soll string _display_name = displayname; // Die Beschreibung der Freigabe string _remark = share.Remark; // Der ShareType ShareType _share_type = share.ShareType; // Ob es eine versteckte Freigabe ist oder nicht bool _hidden = CheckIsShareHidden(share); Console.WriteLine("Share: " + share + " - " + share.Remark); #region Prüfung ob schon vorhanden ist // Der SQL Befehl zum überprüfen ob der jeweilige Eintrag schon vorhanden ist string sql = $"SELECT _path_id FROM {MsSql.TBL_tmp_FS_Shares} WHERE _path_hash = @PathHash"; SqlCommand cmd = new SqlCommand(sql, mssql.Con); // Der Hash wird als Parameter an den SQL Befehl gehängt cmd.Parameters.AddWithValue("@PathHash", _path_hash); // Öffnet die SQL Verbindung, führt die Abfrage durch und schließt die Verbindung wieder mssql.Open(); // Falls es den abgefragten Datensatz schon gibt, bekommt man in index die ID des Datensatzen, sonnst null var _path_id = cmd.ExecuteScalar(); mssql.Close(); #endregion #region Größenberechnung // Es gibt die Zeile long _size; if (_path_id != null) { sql = $"SELECT _size FROM {MsSql.TBL_tmp_FS_Shares} WHERE _path_id = @PathId"; cmd = new SqlCommand(sql, mssql.Con); // Der Hash wird als Parameter an den SQL Befehl gehängt cmd.Parameters.AddWithValue("@PathId", _path_id); // Öffnet die SQL Verbindung, führt die Abfrage durch und schließt die Verbindung wieder mssql.Open(); // Falls es den abgefragten Datensatz schon gibt, bekommt man in index die ID des Datensatzen, sonnst null var size = cmd.ExecuteScalar(); mssql.Close(); if ((long)size == 0 || size == null) { _size = DirSize(dInfo); } else { _size = (long)size; } } else { _size = DirSize(dInfo); } #endregion // Liest alle Unterordner in ein Array DirectoryInfo[] childs; try { childs = dInfo.GetDirectories(); } catch (Exception) { childs = new DirectoryInfo[1]; } // Liest die Infos über den Besitzer aus string _owner_sid = "0"; DirectorySecurity dSecurity = null; try { dSecurity = dInfo.GetAccessControl(); IdentityReference owner = dSecurity.GetOwner(typeof(SecurityIdentifier)); // FÜR SID _owner_sid = owner.Value; } catch (Exception) { } // Ob der Ordner Unterordner hat oder nicht int _has_children = (childs.Length > 0) ? 1 : 0; // Hash ist noch nicht vorhanden if (_path_id == null) { // Der SQL Befehl zum INSERT in die Datenbank sql = $"INSERT INTO {MsSql.TBL_tmp_FS_Shares}(_unc_path_name, _owner_sid, _has_children, _size, _path_hash, _path_name, _display_name, _remark, _share_type, _hidden) " + $"OUTPUT INSERTED._path_id " + $"VALUES (@UncPathName, @OwnerSid, @HasChildren, @Size, @PathHash, @PathName, @DisplayName, @Remark, @ShareType, @Hidden) "; cmd = new SqlCommand(sql, mssql.Con); // Hängt die Parameter an cmd.Parameters.AddWithValue("@UncPathName", _unc_path_name); cmd.Parameters.AddWithValue("@OwnerSid", _owner_sid); cmd.Parameters.AddWithValue("@HasChildren", _has_children); cmd.Parameters.AddWithValue("@Size", _size); cmd.Parameters.AddWithValue("@PathHash", _path_hash); cmd.Parameters.AddWithValue("@PathName", _path_name); cmd.Parameters.AddWithValue("@DisplayName", _display_name); cmd.Parameters.AddWithValue("@Remark", _remark); cmd.Parameters.AddWithValue("@ShareType", _share_type.ToString()); cmd.Parameters.AddWithValue("@Hidden", _hidden); // Öffnet die SQL Verbindung mssql.Open(); // Führt die Query aus _path_id = (int)cmd.ExecuteScalar(); //Schließt die Verbindung mssql.Close(); } // Hash ist noch nicht vorhanden else { // SQL Befehl zum Updaten des Eintrags sql = $"UPDATE {MsSql.TBL_tmp_FS_Shares} " + $"SET _unc_path_name = @UncPathName, _owner_sid = @OwnerSid, _has_children = @HasChildren, _size = @Size, _path_hash = @PathHash, " + $"_path_name = @PathName, _display_name = @DisplayName, _remark = @Remark, _share_type = @ShareType, _hidden = @Hidden " + $"WHERE _path_id = @PathId"; cmd = new SqlCommand(sql, mssql.Con); // Hängt die Parameter an cmd.Parameters.AddWithValue("@UncPathName", _unc_path_name); cmd.Parameters.AddWithValue("@OwnerSid", _owner_sid); cmd.Parameters.AddWithValue("@HasChildren", _has_children); cmd.Parameters.AddWithValue("@Size", _size); cmd.Parameters.AddWithValue("@PathHash", _path_hash); cmd.Parameters.AddWithValue("@PathName", _path_name); cmd.Parameters.AddWithValue("@DisplayName", _display_name); cmd.Parameters.AddWithValue("@Remark", _remark); cmd.Parameters.AddWithValue("@ShareType", _share_type); cmd.Parameters.AddWithValue("@Hidden", _hidden); cmd.Parameters.AddWithValue("@PathId", (int)_path_id); // Öffnet die SQL Verbindung mssql.Open(); // Führt die Query aus cmd.ExecuteNonQuery(); //Schließt die Verbindung mssql.Close(); } // Ruft die ACL zum jeweiligen Ordner ab und schreib diese in die Datenbank if (dSecurity != null) { GetACEs(dSecurity, (int)_path_id, 1); } // Geht über alle Unterordner (Kinder) und ruft die Funktion rekursiv auf foreach (DirectoryInfo child in childs) { GetDirectorySecurity(child, (int)_path_id); } }
public static void TraverseTree(string root) { // Data structure to hold names of subfolders to be // examined for files. Stack <string> dirs = new Stack <string>(20); if (!System.IO.Directory.Exists(root)) { throw new ArgumentException(); } dirs.Push(root); while (dirs.Count > 0) { string currentDir = dirs.Pop(); form.label_status.Text = "Processing folder: " + currentDir; System.Windows.Forms.Application.DoEvents(); string[] subDirs; try { subDirs = System.IO.Directory.GetDirectories(currentDir); } // An UnauthorizedAccessException exception will be thrown if we do not have // discovery permission on a folder or file. It may or may not be acceptable // to ignore the exception and continue enumerating the remaining files and // folders. It is also possible (but unlikely) that a DirectoryNotFound exception // will be raised. This will happen if currentDir has been deleted by // another application or thread after our call to Directory.Exists. The // choice of which exceptions to catch depends entirely on the specific task // you are intending to perform and also on how much you know with certainty // about the systems on which this code will run. catch (UnauthorizedAccessException e) { MessageBox.Show(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { MessageBox.Show(e.Message); continue; } string[] files = null; try { string security = ""; DirectorySecurity dSecurity = System.IO.Directory.GetAccessControl(currentDir); string author = dSecurity.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(); AuthorizationRuleCollection acl = dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); foreach (FileSystemAccessRule ace in acl) { if (ace.IdentityReference.Value != "NT AUTHORITY\\SYSTEM") { security += "Account:" + ace.IdentityReference.Value + " | " + "Type:" + ace.AccessControlType + " | " + "Rights:" + ace.FileSystemRights + " | " + "Inherited:" + ace.IsInherited + "\n"; } } //Name, Extension, Folders, Author, Created, Modified, Security, Size, Status filetable.Rows.Add(null, currentDir.Substring(folderstartpos), null, null, null, null, null, null, security, null, "folder"); files = System.IO.Directory.GetFiles(currentDir); } catch (UnauthorizedAccessException e) { MessageBox.Show(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { MessageBox.Show(e.Message); continue; } // Perform the required action on each file here. // Modify this block to perform your required task. foreach (string file in files) { string status = "Success"; string security = ""; try { // Perform whatever action is required in your scenario. if (file != @"x:\TOH Activities\Youth Work\Youthwork Team\TOH.accde") { System.IO.FileInfo fi = new System.IO.FileInfo(file); string extn = fi.Extension.ToLower(); if (fi.Name.StartsWith("~")) { status = "Starts with ~"; } else if (!allowedfiles.Any(extn.Contains)) { status = "Excluded Extension"; } //string author = System.IO.File.GetAccessControl(file).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(); FileSecurity fSecurity = System.IO.File.GetAccessControl(file); string author = fSecurity.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(); AuthorizationRuleCollection acl = fSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); foreach (FileSystemAccessRule ace in acl) { if (ace.IdentityReference.Value != "NT AUTHORITY\\SYSTEM") { security += "Account:" + ace.IdentityReference.Value + " | " + "Type:" + ace.AccessControlType + " | " + "Rights:" + ace.FileSystemRights + " | " + "Inherited:" + ace.IsInherited + "\n"; } } //CTR, FileName, Version, Extension, Folders, Author, Created, Modified, Security, Size, Status int version = 0; DataRow dr = (from r in filetable.AsEnumerable() where (string)r["Name"] == fi.Name orderby r["version"] descending select r).FirstOrDefault(); if (dr != null) { if ((int)dr["version"] == 0) { dr["version"] = 1; } version = (int)dr["version"] + 1; } filetable.Rows.Add(null, fi.Name, version, extn, fi.DirectoryName.Substring(folderstartpos), author, fi.CreationTimeUtc, fi.LastWriteTimeUtc, security, fi.Length, status); } } catch (System.IO.FileNotFoundException e) { // If file was deleted by a separate application // or thread since the call to TraverseTree() // then just continue. MessageBox.Show(e.Message); continue; } } // Push the subdirectories onto the stack for traversal. // This could also be done before handing the files. foreach (string str in subDirs) { dirs.Push(str); } } if (doExcel) { form.label_status.Text = "Creating Excel Analasis document (" + ExcelFile + ")"; System.Windows.Forms.Application.DoEvents(); ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial; using (var p = new ExcelPackage()) { { //ALL var wsAll = p.Workbook.Worksheets.Add("All"); wsAll.Cells["A1"].LoadFromDataTable(filetable, true); //LARGE DataView dvlarge = new DataView(filetable, "[size] > 2000000", "", DataViewRowState.CurrentRows); System.Data.DataTable dtlarge = dvlarge.ToTable(); var wsLarge = p.Workbook.Worksheets.Add("> 2Mb"); wsLarge.Cells["A1"].LoadFromDataTable(dtlarge, true); //TILDE DataView dvTilde = new DataView(filetable, "[Status] = 'Starts with ~'", "", DataViewRowState.CurrentRows); System.Data.DataTable dtTilde = dvTilde.ToTable(); var wsTilde = p.Workbook.Worksheets.Add("Starts with ~"); wsTilde.Cells["A1"].LoadFromDataTable(dtTilde, true); //EXCLUDED EXTENSIONS DataView dvExtension = new DataView(filetable, "[Status] = 'Excluded Extension'", "", DataViewRowState.CurrentRows); System.Data.DataTable dtExtension = dvExtension.ToTable(); var wsExtension = p.Workbook.Worksheets.Add("Excluded Extension"); wsExtension.Cells["A1"].LoadFromDataTable(dtExtension, true); //DataView dvAuthor = new DataView(filetable, "", "", DataViewRowState.CurrentRows); //System.Data.DataTable dtAuthor = dvAuthor.ToTable(true,"Author"); //var wsAuthor = p.Workbook.Worksheets.Add("Author"); //wsAuthor.Cells["A1"].LoadFromDataTable(dtAuthor, true); //AUTHORS var results = from row in filetable.AsEnumerable() group row by row.Field <string>("Author") into g select new { AuthorName = g.Key, Count = g.Count() }; DataTable queryResults = new DataTable(); queryResults.Columns.Add("AuthorName", typeof(string)); queryResults.Columns.Add("Count", typeof(int)); foreach (var result in results) { queryResults.Rows.Add(new object[] { result.AuthorName, result.Count }); } var wsAuthor = p.Workbook.Worksheets.Add("Author"); wsAuthor.Cells["A1"].LoadFromDataTable(queryResults, true); //SITE USERS var wsSiteusers = p.Workbook.Worksheets.Add("Site Users"); wsSiteusers.Cells["A1"].LoadFromDataTable(siteuserstable, true); //DUPLICATES DataView dvDuplicate = new DataView(filetable, "[Version] <> 0 and [Status] = 'Success'", "", DataViewRowState.CurrentRows); dvDuplicate.Sort = "Name ASC, Version ASC"; System.Data.DataTable dtDuplicate = dvDuplicate.ToTable(); var wsDuplicate = p.Workbook.Worksheets.Add("Duplicates"); wsDuplicate.Cells["A1"].LoadFromDataTable(dtDuplicate, true); //SUMMARY var Summaryresults = from row in filetable.AsEnumerable() group row by new { Extension = row.Field <string>("Extension"), Status = row.Field <string>("Status") } into g select new { extension = g.Key.Extension, status = g.Key.Status, count = g.Count() }; DataTable dtSummary = new DataTable(); dtSummary.Columns.Add("Status", typeof(string)); dtSummary.Columns.Add("Extension", typeof(string)); dtSummary.Columns.Add("Count", typeof(int)); foreach (var result in Summaryresults) { dtSummary.Rows.Add(new object[] { result.status, result.extension, result.count }); } DataView dvSummary = dtSummary.DefaultView; dvSummary.Sort = "Status ASC, Extension ASC"; DataTable dtSummarySorted = dvSummary.ToTable(); var wsSummary = p.Workbook.Worksheets.Add("Summary"); wsSummary.Cells["A1"].LoadFromDataTable(dtSummarySorted, true); p.SaveAs(new FileInfo(ExcelFile)); } } //Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); //Workbook ExcelWorkBook = ExcelApp.Application.Workbooks.Add(); /* * createworksheet(ExcelWorkBook, 1, "Successful", this.list_success); * createworksheet(ExcelWorkBook, 2, "Errors", this.list_error); * createworksheet(ExcelWorkBook, 3, "Excluded", this.list_exclude); * createworksheet(ExcelWorkBook, 4, "With &", this.list_ampersand); * createworksheet(ExcelWorkBook, 5, "Duplicates", this.list_duplicates); * createworksheet(ExcelWorkBook, 6, "Summary", this.list_summary); * createworksheet(ExcelWorkBook, 7, "> 2mb", this.list_large); //https://www.youtube.com/watch?v=g39RLflzonI&list=PLaIJswamN5lSSYPatSGSG5IC_gZXpBNdv&index=10 * createworksheet(ExcelWorkBook, 8, "Users", this.list_users); * createworksheet(ExcelWorkBook, 9, "Authors", this.list_authors); */ //ExcelWorkBook.SaveAs(@"C:\temp\SharePointMigration.xlsx"); //ExcelWorkBook.Close(); //ExcelApp.Quit(); //Marshal.ReleaseComObject(ExcelWorkSheet); //Marshal.ReleaseComObject(ExcelWorkBook); //Marshal.ReleaseComObject(ExcelApp); } }
static void UpdateTopLevelNodes(OIMNTFS.FilesystemsRow fileSystem) { DirectoryInfo dInfo = null; DirectorySecurity dSecurity = null; string[] topLevelNodePaths = (string[])null; Int64 filesystemID = fileSystem.ID; try { topLevelNodePaths = Directory.GetDirectories(fileSystem.DriveRoot, "*", SearchOption.TopDirectoryOnly); } catch (Exception e) { Console.WriteLine("Directories in {0} cannot be read.", fileSystem.DriveRoot); Console.WriteLine("{0}", e.Message); return; } foreach (string topLevelNodePath in topLevelNodePaths) { if (excludeNodes.Select("'" + topLevelNodePath + "' LIKE excludeNode").Length > 0) { continue; } try { dInfo = new DirectoryInfo(topLevelNodePath); dSecurity = dInfo.GetAccessControl(); } catch (Exception e) { Console.WriteLine("Directory info in {0} cannot be read.", topLevelNodePath); Console.WriteLine("{0}", e.Message); continue; } DateTime lastWrite = dInfo.LastWriteTimeUtc; DateTime lastAccess = dInfo.LastAccessTimeUtc; string ownerSID = null; string owner = null; try { ownerSID = dSecurity.GetOwner(typeof(System.Security.Principal.SecurityIdentifier)).Value; owner = ad.getObjectName(ownerSID); } catch (Exception e) { Console.WriteLine("Unable to read owner of {0}", topLevelNodePath); Console.WriteLine(e.Message); } Boolean isProtected = dSecurity.AreAccessRulesProtected; if (topLevelNodes.Select("FullPath = '" + dInfo.FullName + "'").Length == 0) { Console.WriteLine("Found new node '{0}'", dInfo.FullName); OIMNTFS.TopLevelNodesRow newTopLevelNode = topLevelNodes.NewTopLevelNodesRow(); newTopLevelNode.FilesystemID = filesystemID; newTopLevelNode.ScanDepth = fileSystem.Depth; newTopLevelNode.FullPath = dInfo.FullName; newTopLevelNode.Name = dInfo.Name; newTopLevelNode.LastAccessUTC = dInfo.LastAccessTimeUtc; newTopLevelNode.LastWriteUTC = dInfo.LastWriteTimeUtc; newTopLevelNode.LastScanned = DateTime.MinValue; newTopLevelNode.FirstSeen = DateTime.UtcNow; newTopLevelNode.DataOwner = owner; newTopLevelNode.isProtected = isProtected; topLevelNodes.AddTopLevelNodesRow(newTopLevelNode); } } if (writeDatabase) { topLevelNodesTable.Update(topLevelNodes); } }
private Info CreateInfoFromFileSystemInfo(FileSystemInfo fi) { Info i = new Info { Name = fi.Name, FullName = fi.FullName, IsDirectory = fi is DirectoryInfo, DateOfCreate = fi.CreationTime, DateOfModification = fi.LastWriteTime, DateOfLastAccess = fi.LastAccessTime, SizeInBytes = (fi is DirectoryInfo ? 0 : (fi as FileInfo).Length), IsSystem = (fi.Attributes & FileAttributes.System) == FileAttributes.System, IsReadOnly = (fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly, IsArchive = (fi.Attributes & FileAttributes.Archive) == FileAttributes.Archive, IsCompressed = (fi.Attributes & FileAttributes.Compressed) == FileAttributes.Compressed, IsHidden = (fi.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden, IsTemporary = (fi.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary }; WindowsIdentity wi = WindowsIdentity.GetCurrent(); WindowsPrincipal wp = new WindowsPrincipal(wi); AuthorizationRuleCollection arc = null; if (fi is DirectoryInfo) { DirectorySecurity ds = (fi as DirectoryInfo).GetAccessControl(AccessControlSections.Access); IdentityReference ir = ds.GetOwner(typeof(NTAccount)); if (ir != null) { i.Owner = ir.Value; } arc = ds.GetAccessRules(true, true, typeof(NTAccount)); } else { FileSecurity fs = (fi as FileInfo).GetAccessControl(AccessControlSections.Access); IdentityReference ir = fs.GetOwner(typeof(NTAccount)); if (ir != null) { i.Owner = ir.Value; } arc = fs.GetAccessRules(true, true, typeof(NTAccount)); } foreach (FileSystemAccessRule fsar in arc) { if (wi.Name == fsar.IdentityReference.Value || wp.IsInRole(fsar.IdentityReference.Value)) { if (!i.IsCurrentUserCanRead) { i.IsCurrentUserCanRead = (fsar.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read; } if (!i.IsCurrentUserCanModify) { i.IsCurrentUserCanModify = (fsar.FileSystemRights & FileSystemRights.Modify) == FileSystemRights.Modify; } if (!i.IsCurrentUserCanChangePermissions) { i.IsCurrentUserCanChangePermissions = (fsar.FileSystemRights & FileSystemRights.ChangePermissions) == FileSystemRights.ChangePermissions; } } } return(i); }
/// <summary> /// 获取文件夹相关信息 /// </summary> /// <param name="dir">文件夹info</param> /// <param name="plies">层数</param> /// <returns></returns> public static RecordBean GetDirBean(DirectoryInfo dir, uint plies) { string owner; RecordExCode errorCode; try { DirectorySecurity security = dir.GetAccessControl(); IdentityReference identity = security.GetOwner(typeof(NTAccount)); owner = identity.ToString(); errorCode = RecordExCode.Normal; } catch (IdentityNotMappedException e) { owner = "IdentityNotMappedException"; errorCode = RecordExCode.IdentityNotMappedException; Log.Warn(string.Format("获取文件夹所有者失败。{0} {1}, [error code: {2}]", dir.FullName, e.Message, errorCode)); } catch (ArgumentException e) { owner = "ArgumentException"; errorCode = RecordExCode.ArgumentException; Log.Warn(string.Format("获取文件夹有者失败。{0} {1}, [error code: {2}]", dir.FullName, e.Message.Replace("\r\n", ""), errorCode)); } catch (UnauthorizedAccessException e) { owner = "UnauthorizedAccessException"; errorCode = RecordExCode.ArgumentException; Log.Warn(string.Format("获取文件夹所有者失败。{0} {1}, [error code: {2}]", dir.FullName, e.Message, errorCode)); } catch (InvalidOperationException e) { owner = "InvalidOperationException"; errorCode = RecordExCode.InvalidOperationException; Log.Warn(string.Format("获取文件夹所有者失败。{0} {1}, [error code: {2}]", dir.FullName, e.Message, errorCode)); } catch (FileNotFoundException e) { errorCode = RecordExCode.NotFound; Log.Warn(string.Format("文件夹不存在。{0}, [error code: {1}]", e.Message, errorCode)); return(new RecordBean() { Path = dir.FullName, ExceptionCode = (int)errorCode, }); } return(new RecordBean() { Path = dir.FullName, Plies = plies, CerateTime = dir.CreationTime, Owner = owner, ExceptionCode = (int)errorCode, DirCount = 0, IsFile = false, IsChange = false, }); }
/// <summary> /// Change the ownership of the file or folder that is associated with the ListViewLocker. /// </summary> /// <param name="owned">A boolean to represent wether the operator owns the file or folder that is associated with the ListViewLocker.</param> internal void SetOwnership(bool owned) { try { if (owned) { if (File.GetAttributes(GetPath()).HasFlag(FileAttributes.Directory)) { DirectoryInfo info = new DirectoryInfo(GetPath()); WindowsIdentity self = WindowsIdentity.GetCurrent(); DirectorySecurity ds = info.GetAccessControl(); ds.SetAccessRuleProtection(false, true); if (self?.User == null) { return; } if (ds.GetOwner(typeof(NTAccount)).ToString() != self.Name) { ds.SetOwner(self.User); } ds.AddAccessRule(new FileSystemAccessRule(self.User, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow)); info.SetAccessControl(ds); } else { WindowsIdentity self = WindowsIdentity.GetCurrent(); FileSecurity fs = File.GetAccessControl(GetPath()); fs.SetAccessRuleProtection(false, true); if (self?.User == null) { return; } if (fs.GetOwner(typeof(NTAccount)).ToString() != self.Name) { fs.SetOwner(self.User); } fs.AddAccessRule(new FileSystemAccessRule(self.User, FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAccessControl(GetPath(), fs); File.SetAttributes(GetPath(), FileAttributes.Normal); } } else { if (File.GetAttributes(GetPath()).HasFlag(FileAttributes.Directory)) { DirectoryInfo directoryInfo = new DirectoryInfo(GetPath()); DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(); directorySecurity.SetAccessRuleProtection(true, false); AuthorizationRuleCollection rules = directorySecurity.GetAccessRules(true, true, typeof(NTAccount)); foreach (FileSystemAccessRule rule in rules) { directorySecurity.RemoveAccessRule(rule); } Directory.SetAccessControl(GetPath(), directorySecurity); } else { FileSecurity fs = File.GetAccessControl(GetPath()); fs.SetAccessRuleProtection(true, false); AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(NTAccount)); foreach (FileSystemAccessRule rule in rules) { fs.RemoveAccessRule(rule); } File.SetAccessControl(GetPath(), fs); } } } catch (Exception ex) { MessageBoxAdv.Show(ex.Message, "DeadLock", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void TraverseTree(string root) { // Data structure to hold names of subfolders to be // examined for files. Stack <string> dirs = new Stack <string>(20); if (!System.IO.Directory.Exists(root)) { throw new ArgumentException(); } dirs.Push(root); while (dirs.Count > 0) { string currentDir = dirs.Pop(); form.label_status.Text = "Processing folder: " + currentDir; System.Windows.Forms.Application.DoEvents(); string[] subDirs; try { subDirs = System.IO.Directory.GetDirectories(currentDir); } // An UnauthorizedAccessException exception will be thrown if we do not have // discovery permission on a folder or file. It may or may not be acceptable // to ignore the exception and continue enumerating the remaining files and // folders. It is also possible (but unlikely) that a DirectoryNotFound exception // will be raised. This will happen if currentDir has been deleted by // another application or thread after our call to Directory.Exists. The // choice of which exceptions to catch depends entirely on the specific task // you are intending to perform and also on how much you know with certainty // about the systems on which this code will run. catch (UnauthorizedAccessException e) { //Console.WriteLine(e.Message); form.list_error.Items.Add(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { //Console.WriteLine(e.Message); form.list_error.Items.Add(e.Message); continue; } string[] files = null; try { string security = ""; DirectorySecurity dSecurity = System.IO.Directory.GetAccessControl(currentDir); string author = dSecurity.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(); AuthorizationRuleCollection acl = dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); foreach (FileSystemAccessRule ace in acl) { security += "Account:" + ace.IdentityReference.Value + tab + "Type:" + ace.AccessControlType + tab + "Rights:" + ace.FileSystemRights + tab + "Inherited:" + ace.IsInherited + tab; } form.list_success.Items.Add("Folder" + tab + currentDir + tab + security); files = System.IO.Directory.GetFiles(currentDir); } catch (UnauthorizedAccessException e) { //Console.WriteLine(e.Message); form.list_error.Items.Add(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { //Console.WriteLine(e.Message); form.list_error.Items.Add(e.Message); continue; } // Perform the required action on each file here. // Modify this block to perform your required task. foreach (string file in files) { string security = ""; try { // Perform whatever action is required in your scenario. System.IO.FileInfo fi = new System.IO.FileInfo(file); string extn = fi.Extension.ToLower(); Boolean exclude = false; string key = ""; if (fi.Name.StartsWith("~")) { exclude = true; key = "Failed" + tab + "~"; } else if (!allowedfiles.Any(extn.Contains)) { exclude = true; key = "Failed" + tab + extn; } if (exclude) { form.list_exclude.Items.Add(file); } else { if (fi.Length > 2000000) { form.list_large.Items.Add(file); } //string author = System.IO.File.GetAccessControl(file).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(); FileSecurity fSecurity = System.IO.File.GetAccessControl(file); string author = fSecurity.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(); AuthorizationRuleCollection acl = fSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); foreach (FileSystemAccessRule ace in acl) { security += "Account:" + ace.IdentityReference.Value + tab + "Type:" + ace.AccessControlType + tab + "Rights:" + ace.FileSystemRights + tab + "Inherited:" + ace.IsInherited + tab; } if (!authors.ContainsKey(author)) { authors[author] = 0; } authors[author]++; // = counts[key] + 1; string uniqueFile = file; // + " " + fi.LastWriteTime; string uniqueName = fi.Name; // + " " + fi.LastWriteTime; if (!successfulfiles.ContainsKey(uniqueName)) { successfulfiles[uniqueName] = uniqueFile; } else { successfulfiles[uniqueName] += tab + uniqueFile; } form.list_success.Items.Add("File" + tab + uniqueFile + tab + security); filetable.Rows.Add(uniqueFile, 1, "B", "C"); key = "Success" + tab + extn; } if (!counts.ContainsKey(key)) { counts[key] = 0; } counts[key]++; // = counts[key] + 1; if (fi.Name.Contains("&")) { form.list_ampersand.Items.Add(file); } } catch (System.IO.FileNotFoundException e) { // If file was deleted by a separate application // or thread since the call to TraverseTree() // then just continue. //Console.WriteLine(e.Message); form.list_error.Items.Add(e.Message); continue; } } // Push the subdirectories onto the stack for traversal. // This could also be done before handing the files. foreach (string str in subDirs) { dirs.Push(str); } } foreach (KeyValuePair <string, int> entry in counts) { form.list_summary.Items.Add(entry.Value.ToString() + tab + entry.Key); } foreach (KeyValuePair <string, int> author in authors) { form.list_authors.Items.Add(author.Value.ToString() + tab + author.Key); } foreach (KeyValuePair <string, string> duplicates in successfulfiles) { if (duplicates.Value.Contains(tab)) { form.list_duplicates.Items.Add(duplicates.Value); } } form.label_status.Text = "Creating Excel Analasis document (C:\\temp\\SharePointMigration.xlsx)"; System.Windows.Forms.Application.DoEvents(); /* * using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\temp\SharePointMigration.tsv")) * { * foreach (var item in form.list_success.Items) * { * file.WriteLine("Success" + tab + item.ToString()); * } * foreach (var item in form.list_error.Items) * { * file.WriteLine("Error" + tab + item.ToString()); * } * foreach (var item in form.list_exclude.Items) * { * file.WriteLine("Excluded" + tab + item.ToString()); * } * foreach (var item in form.list_ampersand.Items) * { * file.WriteLine("Ampersand" + tab + item.ToString()); * } * foreach (var item in form.list_duplicates.Items) * { * file.WriteLine("Duplicate" + tab + item.ToString()); * } * foreach (var item in form.list_summary.Items) * { * file.WriteLine("Summary" + tab + item.ToString()); * } * foreach (var item in form.list_large.Items) * { * file.WriteLine("Large" + tab + item.ToString()); * } * foreach (var item in form.list_users.Items) * { * file.WriteLine("Site User" + tab + item.ToString()); * } * foreach (var item in form.list_authors.Items) * { * file.WriteLine("Author" + tab + item.ToString()); * } * } */ if (doExcel) { Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); Workbook ExcelWorkBook = ExcelApp.Application.Workbooks.Add(); createworksheet(ExcelWorkBook, 1, "Successful", form.list_success); createworksheet(ExcelWorkBook, 2, "Errors", form.list_error); createworksheet(ExcelWorkBook, 3, "Excluded", form.list_exclude); createworksheet(ExcelWorkBook, 4, "With &", form.list_ampersand); createworksheet(ExcelWorkBook, 5, "Duplicates", form.list_duplicates); createworksheet(ExcelWorkBook, 6, "Summary", form.list_summary); createworksheet(ExcelWorkBook, 7, "> 2mb", form.list_large); //https://www.youtube.com/watch?v=g39RLflzonI&list=PLaIJswamN5lSSYPatSGSG5IC_gZXpBNdv&index=10 createworksheet(ExcelWorkBook, 8, "Users", form.list_users); createworksheet(ExcelWorkBook, 9, "Authors", form.list_authors); ExcelWorkBook.SaveAs(@"C:\temp\SharePointMigration.xlsx"); ExcelWorkBook.Close(); ExcelApp.Quit(); //Marshal.ReleaseComObject(ExcelWorkSheet); Marshal.ReleaseComObject(ExcelWorkBook); Marshal.ReleaseComObject(ExcelApp); } }
public static void ProcessDirectory(string scanPath, int level, int maxlevel, Int64 TopLevelNodeID, Int64 ParentNodeID) { DateTime start = DateTime.Now; DirectoryInfo dInfo = null; DirectorySecurity dSecurity = null; string fullPath = null; string name = null; string owner = "<unknown>"; DateTime lastAccess; DateTime lastWrite; Boolean isProtected = false; Int64 nodeID = 0; DirectoryInfo tInfo = null; DirectorySecurity tSecurity = null; string targetPath = ""; // check if folder name is too long if (scanPath.Length > 248) { Console.WriteLine("\rPath too long: {0} ({1} characters)", scanPath, scanPath.Length); return; } // Check if foldername is in exclusion list try { if (excludeNodes.Select("'" + scanPath.Replace("'", "''") + "' LIKE excludeNode").Length > 0) { return; } } catch (Exception e) { Console.WriteLine("\rFailed to check exclude list for {0}: {1}.", scanPath, e.Message); // do not return } foldercounter++; // now read directory information try { dInfo = new DirectoryInfo(scanPath); lastAccess = dInfo.LastAccessTimeUtc; lastWrite = dInfo.LastWriteTimeUtc; fullPath = dInfo.FullName; name = dInfo.Name; } catch (Exception e) { Console.WriteLine("\rFailed to read directory info for {0}\n{1}", scanPath, e.Message); return; } // read directory security information try { dSecurity = dInfo.GetAccessControl(AccessControlSections.Owner | AccessControlSections.Access); name = dInfo.Name; } catch (Exception e) { Console.WriteLine("\rFailed to read security info for {0}\n{1}", scanPath, e.Message); return; } // now identify owner try { string SID = dSecurity.GetOwner(typeof(System.Security.Principal.SecurityIdentifier)).Value; owner = ad.getObjectName(SID); isProtected = dSecurity.AreAccessRulesProtected; } catch (Exception e) { Console.WriteLine("\rFailed to read ownership info for {0}\n{1}", scanPath, e.Message); } if (isProtected) { protectedcounter++; } // insert node found into nodes table (previously emptied for related toplevelfolder) if (writeDatabase) { try { nodesTable.Insert(fullPath, name, level, TopLevelNodeID, ParentNodeID, owner, isProtected, lastAccess, lastWrite, DateTime.UtcNow); nodeID = (Int64)getNewNodeID.ExecuteScalar(); } catch (Exception e) { Console.WriteLine("INSERTing new nodes row into DB failed."); Console.WriteLine(e.Message); } } // create copy as target folder if (createCopy) { try { targetPath = targetprefix + fullPath.Replace(":", "_").Replace("\\\\", "__"); tInfo = Directory.CreateDirectory(targetPath); tSecurity = new DirectorySecurity(); } catch (Exception e) { Console.WriteLine("\nFailed to create {0}\n{1}", targetPath, e.Message); targetPath = ""; } } // analyse all access rules (explicit access rules only, no inherited access rules) foreach (FileSystemAccessRule fsar in dSecurity.GetAccessRules(true, false, typeof(System.Security.Principal.SecurityIdentifier))) { entitlementcounter++; string SID = fsar.IdentityReference.Value; string objectName = ad.getObjectName(SID); string objectClass = ad.getObjectClass(SID); string accessRights = fsar.FileSystemRights.ToString(); string accessType = fsar.AccessControlType.ToString(); string rulePropagation = fsar.PropagationFlags.ToString(); string ruleInheritance = fsar.InheritanceFlags.ToString(); if (writeDatabase) { try { entitlementsTable.Insert(nodeID, objectName, objectClass, accessRights, accessType, rulePropagation, ruleInheritance, DateTime.UtcNow); } catch (Exception e) { Console.WriteLine("\rFailed to insert entitlements for {0}\n{1}", objectName, e.Message); return; } } Console.Write("\rLevel {0}, Folders {1}, Entitlements {2}, Protected {3}, Runtime {4} ", level, foldercounter, entitlementcounter, protectedcounter, (DateTime.Now - start).ToString()); } // end foreach fsar if (level < maxlevel) { Console.Write("\rLevel {0}, Folders {1}, Entitlements {2}, Protected {3}, next level ... ", level, foldercounter, entitlementcounter, protectedcounter); string[] subDirectories = null; try { subDirectories = Directory.GetDirectories(dInfo.FullName); } catch (Exception e) { Console.WriteLine("\runable to read subdirectories of {0} ", dInfo.FullName); Console.WriteLine("{0}", e.Message); return; } Console.Write("\rLevel {0}, Folders {1}, Entitlements {2}, Protected {3}, Runtime {4} ", level, foldercounter, entitlementcounter, protectedcounter, (DateTime.Now - start).ToString()); foreach (string subdirectory in subDirectories) { ProcessDirectory(subdirectory, level + 1, maxlevel, TopLevelNodeID, nodeID); } } }
private void FullScan() { eventLog.Buffer("Refreshing file systems table."); fileSystemsTable.ClearBeforeFill = true; fileSystemsTable.Fill(fileSystems); eventLog.Buffer("{0} file systems read.", fileSystems.Count); eventLog.Buffer("Refreshing exclude nodes table."); excludeNodesTable.ClearBeforeFill = true; excludeNodesTable.Fill(excludeNodes); eventLog.Buffer("{0} exclude nodes read.", excludeNodes.Count); foreach (OIMNTFS.FilesystemsRow fileSystem in fileSystems.Rows) { eventLog.Buffer("Reading file system {0}", fileSystem.DriveRoot); service.networkDrive.LocalDrive = fileSystem.DriveRoot.Substring(0, 2); service.networkDrive.Persistent = false; service.networkDrive.SaveCredentials = false; service.networkDrive.Force = true; service.networkDrive.ShareName = "\\\\" + fileSystem.ProviderIP + "\\" + fileSystem.Share; eventLog.Buffer("Mapping drive {0} to {1}", service.networkDrive.LocalDrive, service.networkDrive.ShareName); try { switch (fileSystem.Type) { case 0: service.networkDrive.MapDrive(); break; case 1: service.networkDrive.MapDrive(fileSystem.User, fileSystem.Password); break; default: service.networkDrive.MapDrive(fileSystem.User, fileSystem.Password); break; } } catch (Exception e) { eventLog.Buffer("unable to map drive {0} to {1}", service.networkDrive.LocalDrive, service.networkDrive.ShareName); eventLog.Buffer("{0}", e.ToString()); continue; } eventLog.Buffer("Updating top level folders of {0}...", fileSystem.DriveRoot); DirectoryInfo dInfo = null; DirectorySecurity dSecurity = null; string[] topLevelNodePaths = (string[])null; Int64 filesystemID = fileSystem.ID; try { topLevelNodePaths = Directory.GetDirectories(fileSystem.DriveRoot, "*", SearchOption.TopDirectoryOnly); } catch (Exception e) { eventLog.Buffer("Directories in {0} cannot be read.", fileSystem.DriveRoot); eventLog.Buffer("{0}", e.Message); continue; } foreach (string topLevelNodePath in topLevelNodePaths) { if (excludeNodes.Select("'" + topLevelNodePath + "' LIKE excludeNode").Length > 0) { continue; } try { dInfo = new DirectoryInfo(topLevelNodePath); dSecurity = dInfo.GetAccessControl(); } catch (Exception e) { eventLog.Buffer("Directory info in {0} cannot be read.", topLevelNodePath); eventLog.Buffer("{0}", e.Message); continue; } DateTime lastWrite = dInfo.LastWriteTimeUtc; DateTime lastAccess = dInfo.LastAccessTimeUtc; string ownerSID = null; string owner = null; try { ownerSID = dSecurity.GetOwner(typeof(System.Security.Principal.SecurityIdentifier)).Value; owner = service.adCache.getObjectName(ownerSID); } catch (Exception e) { eventLog.Buffer("Unable to read owner of {0}", topLevelNodePath); eventLog.Buffer(e.Message); } Boolean isProtected = dSecurity.AreAccessRulesProtected; if (topLevelNodes.Select("FullPath = '" + dInfo.FullName + "'").Length == 0) { eventLog.Buffer("Found new node '{0}'", dInfo.FullName); OIMNTFS.TopLevelNodesRow newTopLevelNode = topLevelNodes.NewTopLevelNodesRow(); newTopLevelNode.FilesystemID = filesystemID; newTopLevelNode.ScanDepth = fileSystem.Depth; newTopLevelNode.FullPath = dInfo.FullName; newTopLevelNode.Name = dInfo.Name; newTopLevelNode.LastAccessUTC = dInfo.LastAccessTimeUtc; newTopLevelNode.LastWriteUTC = dInfo.LastWriteTimeUtc; newTopLevelNode.LastScanned = DateTime.MinValue; newTopLevelNode.FirstSeen = DateTime.UtcNow; newTopLevelNode.DataOwner = owner; newTopLevelNode.isProtected = isProtected; topLevelNodes.AddTopLevelNodesRow(newTopLevelNode); } } topLevelNodesTable.Update(topLevelNodes); } // now start to process all top level nodes foreach (OIMNTFS.TopLevelNodesRow topLevelNode in topLevelNodes.OrderBy(n => n.LastScanned)) { eventLog.Buffer("Scanning {0} down to level {1}...", topLevelNode.FullPath, topLevelNode.ScanDepth); try { // if scanner is working on same top level node, wait for it to complete while (service.scanner.CurrentTopLevelNode() == topLevelNode.ID) { this.eventLog.Write("FullScan is waiting for single scan below {0} to complete.", topLevelNode.FullPath); System.Threading.Thread.Sleep(5000); // busy wait :-( } _CurrentTopLevelNode = topLevelNode.ID; start = DateTime.Now; _FolderCounter = 0; _EntitlementCounter = 0; _ProtectedCounter = 0; ProcessNode(topLevelNode.FullPath, 1, topLevelNode.ScanDepth, topLevelNode.ID, 0); eventLog.Buffer("Done."); eventLog.Buffer("Updating database..."); try { // first delete old values eventLog.Buffer("Deleting old scan information for {0}...", topLevelNode.FullPath); SqlCommand delnodes = conn.CreateCommand(); delnodes.CommandText = string.Format("DELETE FROM [OIMNTFS].[dbo].[Nodes] WHERE TopLevelNodeID = {0}", topLevelNode.ID); delnodes.ExecuteNonQuery(); // update last scanned timestamp (topLevelNodes.FindByID(topLevelNode.ID)).LastScanned = DateTime.Now; // now update (insert) nodes processed topLevelNodesTable.Update(topLevelNodes); } catch (Exception e) { eventLog.Buffer("Failed to update last scanned timestamp for {0}", topLevelNode.FullPath); eventLog.Buffer(e.Message); } eventLog.Buffer("{0} completed on {1:hh:mm:ss}.\n{2} folders read ({3:0.0} folders per second)\n", topLevelNode.FullPath, DateTime.Now, _FolderCounter, _FolderCounter / (DateTime.Now - start).TotalSeconds, _FolderCounter); // Update last access and last write timestamp on TopLevelFolders string cmdtext = @" WITH NodesMax AS ( SELECT TopLevelNodes.ID, maxlastaccess = MAX(LastAccess), maxlastwrite = MAX(LastWrite) FROM TopLevelNodes JOIN Nodes ON Nodes.TopLevelNodeID = TopLevelNodes.ID GROUP BY TopLevelNodes.ID ) UPDATE TopLevelNodes SET LastTreeAccessUTC = NodesMax.maxlastaccess, LastTreeWriteUTC = NodesMax.maxlastwrite FROM ToplevelNodes JOIN NodesMax ON NodesMax.ID = TopLevelNodes.ID"; (new SqlCommand(cmdtext, conn)).ExecuteNonQuery(); eventLog.Flush(); } catch (Exception e) { this.eventLog.Write("Exception during scan below {0}: {1}", topLevelNode.FullPath, e.Message); eventLog.Buffer("Exception during scan below {0}: {1}", topLevelNode.FullPath, e.Message); } finally { _CurrentTopLevelNode = 0; eventLog.Flush(); } } }
public static ActionResult ReadConfig_IMCAC(Session session) { /* * When the installation begins, there may be a previous installation with existing config. * If existing config is found, we need to verify that it is in a secure state. If it is * secure then it will be used as is, unchanged. * * We will read the values from existing config to possibly display in the GUI, but it will * be for informational purposes only. The only CONFIG_TYPES that will be edited are * DEFAULT and CUSTOM. * * The two config options and their defaults are: * - master: salt * - id: hostname * * If the CONFIG_TYPE is not "Existing", and the master and minion id are not the defaults, * then those values will be used to update either the Default config or a Custom config. * * This function writes msi properties: * - MASTER * - MINION_ID * - CONFIG_TYPE * * A GUI installation can show these msi properties because this function is called before the GUI. */ session.Log("...BEGIN ReadConfig_IMCAC"); string ProgramData = System.Environment.GetEnvironmentVariable("ProgramData"); string oldRootDir = @"C:\salt"; string newRootDir = Path.Combine(ProgramData, @"Salt Project\Salt"); // Create msi proporties session["ROOTDIR_old"] = oldRootDir; session["ROOTDIR_new"] = newRootDir; string abortReason = ""; // Insert the first abort reason here if (abortReason.Length > 0) { session["AbortReason"] = abortReason; } session.Log("...Looking for existing config"); string REGISTRY_ROOTDIR = session["EXISTING_ROOTDIR"]; // From registry string reg_config = ""; if (REGISTRY_ROOTDIR.Length > 0) { reg_config = REGISTRY_ROOTDIR + @"\conf\minion"; } // Search for configuration in this order: registry, new layout, old layout string minion_config_file = cutil.get_file_that_exist(session, new string[] { reg_config, newRootDir + @"\conf\minion", oldRootDir + @"\conf\minion" }); string minion_config_dir = ""; // Check for a minion.d directory if (File.Exists(minion_config_file)) { string minion_dot_d_dir = minion_config_file + ".d"; session.Log("...minion_dot_d_dir = " + minion_dot_d_dir); if (Directory.Exists(minion_dot_d_dir)) { session.Log("... folder exists minion_dot_d_dir = " + minion_dot_d_dir); DirectorySecurity dirSecurity = Directory.GetAccessControl(minion_dot_d_dir); IdentityReference sid = dirSecurity.GetOwner(typeof(SecurityIdentifier)); session.Log("...owner of the minion config dir " + sid.Value); } else { session.Log("... folder does not exist: " + minion_dot_d_dir); } } // Check for existing config if (File.Exists(minion_config_file)) { // We found an existing config session["CONFIG_TYPE"] = "Existing"; // Make sure the directory where the config was found is secure minion_config_dir = Path.GetDirectoryName(minion_config_file); // Owner must be one of "Local System" or "Administrators" // It looks like the NullSoft installer sets the owner to // Administrators while the MSI installer sets the owner to // Local System. Salt only sets the owner of the `C:\salt` // directory when it starts and doesn't concern itself with the // conf directory. So we have to check for both. List <string> valid_sids = new List <string>(); valid_sids.Add("S-1-5-18"); //Local System valid_sids.Add("S-1-5-32-544"); //Administrators // Get the SID for the owner of the conf directory FileSecurity fileSecurity = File.GetAccessControl(minion_config_dir); IdentityReference sid = fileSecurity.GetOwner(typeof(SecurityIdentifier)); session.Log("...owner of the minion config file " + sid.Value); // Check to see if it's in the list of valid SIDs if (!valid_sids.Contains(sid.Value)) { // If it's not in the list we don't want to use it. Do the following: // - set INSECURE_CONFIG_FOUND to the insecure config dir // - set CONFIG_TYPE to Default session.Log("...Insecure config found, using default config"); session["INSECURE_CONFIG_FOUND"] = minion_config_dir; session["CONFIG_TYPE"] = "Default"; session["GET_CONFIG_TEMPLATE_FROM_MSI_STORE"] = "True"; // Use template instead } } else { session["GET_CONFIG_TEMPLATE_FROM_MSI_STORE"] = "True"; // Use template } // Set the default values for master and id String master_from_previous_installation = ""; String id_from_previous_installation = ""; // Read master and id from main config file (if such a file exists) if (minion_config_file.Length > 0) { read_master_and_id_from_file_IMCAC(session, minion_config_file, ref master_from_previous_installation, ref id_from_previous_installation); } // Read master and id from minion.d/*.conf (if they exist) if (Directory.Exists(minion_config_dir)) { var conf_files = System.IO.Directory.GetFiles(minion_config_dir, "*.conf"); foreach (var conf_file in conf_files) { if (conf_file.Equals("_schedule.conf")) { continue; } // skip _schedule.conf read_master_and_id_from_file_IMCAC(session, conf_file, ref master_from_previous_installation, ref id_from_previous_installation); } } if (session["MASTER"] == "") { session["MASTER"] = "salt"; } if (session["MINION_ID"] == "") { session["MINION_ID"] = "hostname"; } session.Log("...CONFIG_TYPE msi property = " + session["CONFIG_TYPE"]); session.Log("...MASTER msi property = " + session["MASTER"]); session.Log("...MINION_ID msi property = " + session["MINION_ID"]); // A list of config types that will be edited. Existing config will NOT be edited List <string> editable_types = new List <string>(); editable_types.Add("Default"); editable_types.Add("Custom"); if (editable_types.Contains(session["CONFIG_TYPE"])) { // master if (master_from_previous_installation != "") { session.Log("...MASTER kept config =" + master_from_previous_installation); session["MASTER"] = master_from_previous_installation; session["CONFIG_FOUND"] = "True"; session.Log("...MASTER set to kept config"); } // minion id if (id_from_previous_installation != "") { session.Log("...MINION_ID kept config =" + id_from_previous_installation); session.Log("...MINION_ID set to kept config "); session["MINION_ID"] = id_from_previous_installation; } } // Save the salt-master public key // This assumes the install is silent. // Saving should only occur in WriteConfig_DECAC, // IMCAC is easier and no harm because there is no public master key in the installer. string MASTER_KEY = cutil.get_property_IMCAC(session, "MASTER_KEY"); string ROOTDIR = cutil.get_property_IMCAC(session, "ROOTDIR"); string pki_minion_dir = Path.Combine(ROOTDIR, @"conf\minion.d\pki\minion"); var master_key_file = Path.Combine(pki_minion_dir, "minion_master.pub"); session.Log("...master_key_file = " + master_key_file); bool MASTER_KEY_set = MASTER_KEY != ""; session.Log("...master key earlier config file exists = " + File.Exists(master_key_file)); session.Log("...master key msi property given = " + MASTER_KEY_set); if (MASTER_KEY_set) { String master_key_lines = ""; // Newline after 64 characters int count_characters = 0; foreach (char character in MASTER_KEY) { master_key_lines += character; count_characters += 1; if (count_characters % 64 == 0) { master_key_lines += Environment.NewLine; } } string new_master_pub_key = "-----BEGIN PUBLIC KEY-----" + Environment.NewLine + master_key_lines + Environment.NewLine + "-----END PUBLIC KEY-----"; if (!Directory.Exists(pki_minion_dir)) { // The <Directory> declaration in Product.wxs does not create the folders Directory.CreateDirectory(pki_minion_dir); } File.WriteAllText(master_key_file, new_master_pub_key); } session.Log("...END ReadConfig_IMCAC"); return(ActionResult.Success); }
// рекурсивный перебор директорий void AddDirectories(TreeNode node) { dirSize = 0; string strPath = node.FullPath; DirectoryInfo dir = new DirectoryInfo(strPath); // Объявляем ссылку на массив подкаталогов текущего каталога DirectoryInfo[] arrayDirInfo; node.Nodes.Clear(); arrayDirInfo = dir.GetDirectories(); // Добавляем прочитанные подкаталоги как узлы в дерево // и записываем инфо о них в список foreach (DirectoryInfo dirInfo in arrayDirInfo) { // Создаем новый узел с именем подкаталога TreeNode nodeDir = new TreeNode(dirInfo.Name); // Добавляем его как дочерний к текущему узлу node.Nodes.Add(nodeDir); AddDirectories(nodeDir); } string dirfsar = ""; DirectorySecurity dirSecurity = dir.GetAccessControl(); IdentityReference dirIdentityRef = dirSecurity.GetOwner(typeof(NTAccount)); foreach (FileSystemAccessRule permission in dirSecurity.GetAccessRules(true, true, typeof(NTAccount))) { dirfsar += permission.FileSystemRights.ToString(); // AccessControlType ? } // записываем информацию о файлах в директории foreach (FileInfo file in dir.GetFiles()) { FileSecurity fileSecurity = file.GetAccessControl(); IdentityReference identityRef = fileSecurity.GetOwner(typeof(NTAccount)); string fsar = ""; foreach (FileSystemAccessRule permission in fileSecurity.GetAccessRules(true, true, typeof(NTAccount))) { fsar += permission.FileSystemRights.ToString(); } dirSize += file.Length; Elements.Add(new Items() { Name = file.Name, CreationTime = file.CreationTime.ToString(), LastWriteTime = file.LastWriteTime.ToString(), LastAccessTime = file.LastAccessTime.ToString(), Attributes = file.Attributes.ToString(), Size = file.Length.ToString(), Owner = identityRef.ToString(), Permission = fsar, }); } // добавляем инфо о директории Elements.Add(new Items() { Name = dir.Name, CreationTime = dir.CreationTime.ToString(), LastWriteTime = dir.LastWriteTime.ToString(), LastAccessTime = dir.LastAccessTime.ToString(), Attributes = dir.Attributes.ToString(), Size = dirSize.ToString(), Owner = dirIdentityRef.ToString(), Permission = dirfsar, }); }