public void Test_System___AnalyzeSecurity_LocalAcessShouldNotExist() { string testDir = GetTempDirectoryName(); SetSecuritySystem(testDir); var dirsec = new System.IO.DirectoryInfo(testDir + @"\inherited").GetAccessControl(); AuthorizationRuleCollection accessRules = dirsec.GetAccessRules(true, true, targetType: typeof(SecurityIdentifier)); Assert.IsFalse(HasLocalAces(accessRules), "local access rules found"); }
private static void SetSecuritySystem(string directory) { //create the test structure if (System.IO.Directory.Exists(directory)) { System.IO.Directory.Delete(directory, true); } System.IO.Directory.CreateDirectory(directory); System.IO.Directory.CreateDirectory(System.IO.Path.Combine(directory, "inherited")); System.IO.DirectoryInfo testDirInfo = new System.IO.DirectoryInfo(directory); var ds = testDirInfo.GetAccessControl(AccessControlSections.Access); ds.SetAccessRuleProtection(true, false); ds.AddAccessRule(new FileSystemAccessRule( identity: new SecurityIdentifier(WellKnownSidType.WorldSid, null), fileSystemRights: FileSystemRights.FullControl, inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, propagationFlags: PropagationFlags.None, type: AccessControlType.Allow )); testDirInfo.SetAccessControl(ds); }
private static void DumpClassDirectoryInfo(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); string tempPath = Path.Combine(Path.GetTempPath(), "DirectoryInfo()-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); int expectedLastError; string expectedException; string nonExistingDirectory = SysRoot32 + @"\NonExistingDirectory-" + Path.GetRandomFileName(); if (!isLocal) nonExistingDirectory = Path.LocalToUnc(nonExistingDirectory); string sysDrive = SysDrive; if (!isLocal) sysDrive = Path.LocalToUnc(sysDrive); string sysRoot = SysRoot; if (!isLocal) sysRoot = Path.LocalToUnc(sysRoot); string letter = DriveInfo.GetFreeDriveLetter() + @":\"; if (!isLocal) letter = Path.LocalToUnc(letter); #endregion // Setup #region NotSupportedException expectedLastError = (int) (isLocal ? Win32Errors.ERROR_ENVVAR_NOT_FOUND : Win32Errors.NERR_UseNotFound); expectedException = "System.NotSupportedException"; bool exception = false; try { Console.WriteLine("\nCatch: [{0}]: The given path's format is not supported.", expectedException); string invalidPath = SysDrive + @"\:a"; if (!isLocal) invalidPath = Path.LocalToUnc(invalidPath) + @":a"; DirectoryInfo di = new DirectoryInfo(invalidPath); } catch (Exception ex) { // Not reliable. //var win32Error = new Win32Exception("", ex); //Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); //Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError)); string exceptionTypeName = ex.GetType().FullName; if (exceptionTypeName.Equals(expectedException)) { exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } else Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // NotSupportedException #region Current Directory tempPath = Path.CurrentDirectoryPrefix; if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput Directory Path (Current directory): [{0}]\n", tempPath); StopWatcher(true); System.IO.DirectoryInfo expected = new System.IO.DirectoryInfo(tempPath); Console.WriteLine("\tSystem.IO DirectoryInfo(){0}", Reporter()); StopWatcher(true); DirectoryInfo actual = new DirectoryInfo(tempPath); Console.WriteLine("\tAlphaFS DirectoryInfo(){0}", Reporter()); // Compare values of both instances. CompareDirectoryInfos(expected, actual); #endregion // Current Directory #region Non-Existing Directory Console.WriteLine("\nInput Directory Path: [{0}]\n", nonExistingDirectory); StopWatcher(true); expected = new System.IO.DirectoryInfo(tempPath); Console.WriteLine("\tSystem.IO DirectoryInfo(){0}", Reporter()); StopWatcher(true); actual = new DirectoryInfo(tempPath); Console.WriteLine("\tAlphaFS DirectoryInfo(){0}", Reporter()); // Compare values of both instances. CompareDirectoryInfos(expected, actual); #endregion // Non-Existing Directory #region Existing Directory tempPath = Path.Combine(Path.GetTempPath(), "DirectoryInfo()-Directory-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); try { Directory.CreateDirectory(tempPath); Console.WriteLine("\n\nInput Directory Path: [{0}]\n", tempPath); StopWatcher(true); expected = new System.IO.DirectoryInfo(tempPath); Console.WriteLine("\tSystem.IO DirectoryInfo(){0}", Reporter()); StopWatcher(true); actual = new DirectoryInfo(tempPath); Console.WriteLine("\tAlphaFS DirectoryInfo(){0}", Reporter()); // Compare values of both instances. CompareDirectoryInfos(expected, actual); } finally { Directory.Delete(tempPath); Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed."); } #endregion // Existing Directory #region Method .ToString() Console.WriteLine("\nMethod .ToString()"); Console.WriteLine("Both strings should be the same.\n"); expected = new System.IO.DirectoryInfo("ToString()-TestDirectory"); actual = new DirectoryInfo("ToString()-TestDirectory"); string expectedToString = expected.ToString(); string actualToString = actual.ToString(); Console.WriteLine("\tSystem.IO: [{0}]", expectedToString); Console.WriteLine("\tAlphaFS : [{0}]", actualToString); Assert.AreEqual(expectedToString, actualToString, false); Console.WriteLine(); #endregion Method .ToString() }
private void DumpRefresh(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); string tempPathSysIo = Path.GetTempPath("DirectoryInfo.Refresh()-directory-SysIo-" + Path.GetRandomFileName()); string tempPath = Path.GetTempPath("DirectoryInfo.Refresh()-directory-AlphaFS-" + Path.GetRandomFileName()); if (!isLocal) { tempPathSysIo = Path.LocalToUnc(tempPathSysIo); } if (!isLocal) { tempPath = Path.LocalToUnc(tempPath); } Console.WriteLine("\nInput Directory Path: [{0}]", tempPath); #endregion // Setup #region Refresh try { System.IO.DirectoryInfo diSysIo = new System.IO.DirectoryInfo(tempPathSysIo); DirectoryInfo di = new DirectoryInfo(tempPath); bool existsSysIo = diSysIo.Exists; bool exists = di.Exists; Console.WriteLine("\nnew DirectoryInfo(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Create(); di.Create(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Create(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Delete(); di.Delete(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Delete(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); } finally { if (Directory.Exists(tempPathSysIo)) { Directory.Delete(tempPathSysIo); Assert.IsFalse(Directory.Exists(tempPathSysIo), "Cleanup failed: Directory should have been removed."); } if (Directory.Exists(tempPath)) { Directory.Delete(tempPath); Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed."); } Console.WriteLine(); } #endregion // Refresh }
private static void SetSecuritySystem(string directory) { //create the test structure if (System.IO.Directory.Exists(directory)) System.IO.Directory.Delete(directory, true); System.IO.Directory.CreateDirectory(directory); System.IO.Directory.CreateDirectory(System.IO.Path.Combine(directory, "inherited")); System.IO.DirectoryInfo testDirInfo = new System.IO.DirectoryInfo(directory); var ds = testDirInfo.GetAccessControl(AccessControlSections.Access); ds.SetAccessRuleProtection(true, false); ds.AddAccessRule(new FileSystemAccessRule( identity: new SecurityIdentifier(WellKnownSidType.WorldSid, null), fileSystemRights: FileSystemRights.FullControl, inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, propagationFlags: PropagationFlags.None, type: AccessControlType.Allow )); testDirInfo.SetAccessControl(ds); }
private void DumpRefresh(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); string tempPathSysIo = Path.GetTempPath("DirectoryInfo.Refresh()-directory-SysIo-" + Path.GetRandomFileName()); string tempPath = Path.GetTempPath("DirectoryInfo.Refresh()-directory-AlphaFS-" + Path.GetRandomFileName()); if (!isLocal) tempPathSysIo = Path.LocalToUnc(tempPathSysIo); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput Directory Path: [{0}]", tempPath); #endregion // Setup #region Refresh try { System.IO.DirectoryInfo diSysIo = new System.IO.DirectoryInfo(tempPathSysIo); DirectoryInfo di = new DirectoryInfo(tempPath); bool existsSysIo = diSysIo.Exists; bool exists = di.Exists; Console.WriteLine("\nnew DirectoryInfo(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Create(); di.Create(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Create(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Delete(); di.Delete(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Delete(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); } finally { if (Directory.Exists(tempPathSysIo)) { Directory.Delete(tempPathSysIo); Assert.IsFalse(Directory.Exists(tempPathSysIo), "Cleanup failed: Directory should have been removed."); } if (Directory.Exists(tempPath)) { Directory.Delete(tempPath); Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed."); } Console.WriteLine(); } #endregion // Refresh }
private void DumpCreateDirectory(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); // Directory depth level. int level = new Random().Next(1, 1000); #if NET35 string emspace = "\u3000"; string tempPath = Path.GetTempPath("Directory.CreateDirectory()-" + level + "-" + Path.GetRandomFileName() + emspace); #else // MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameter before deleting the directory. string tempPath = Path.GetTempPath("Directory.CreateDirectory()-" + level + "-" + Path.GetRandomFileName()); #endif if (!isLocal) tempPath = Path.LocalToUnc(tempPath); int expectedLastError; string expectedException; string report; bool exist; #endregion // Setup try { #region IOException using (File.Create(tempPath)) { } expectedLastError = (int)Win32Errors.ERROR_ALREADY_EXISTS; expectedException = "System.IO.IOException"; bool exception = false; try { Console.WriteLine("\nCatch: [{0}]: File already exist with same name.", typeof(IOException).FullName); Directory.CreateDirectory(tempPath); } catch (AlreadyExistsException ex) { Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError)); exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); File.Delete(tempPath); Assert.IsFalse(File.Exists(tempPath), "Cleanup failed: File should have been removed."); #endregion // IOException #region DirectoryNotFoundException (Local) / IOException (Network) expectedLastError = (int)(isLocal ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_BAD_NET_NAME); expectedException = isLocal ? "System.IO.DirectoryNotFoundException" : "System.IO.IOException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: The specified path is invalid (for example, it is on an unmapped drive).", expectedException); #if NET35 string letter = DriveInfo.GetFreeDriveLetter() + @":\shouldFail" + emspace; #else // MSDN: .NET 4+: Trailing spaces are removed from the end of the path parameter before deleting the directory. string letter = DriveInfo.GetFreeDriveLetter() + @":\Non-Existing"; #endif if (!isLocal) letter = Path.LocalToUnc(letter); Directory.CreateDirectory(letter); } catch (Exception ex) { var win32Error = new Win32Exception("", ex); Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); string exceptionTypeName = ex.GetType().FullName; if (exceptionTypeName.Equals(expectedException)) { exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } else Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // DirectoryNotFoundException (Local) / IOException (Network) #region ArgumentException expectedException = "System.ArgumentException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: Path is prefixed with, or contains, only a colon character (:).", expectedException); Directory.CreateDirectory(@":AAAAAAAAAA"); } catch (ArgumentException ex) { exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // ArgumentException #region NotSupportedException expectedLastError = (int)(isLocal ? Win32Errors.ERROR_FILE_EXISTS : Win32Errors.NERR_UseNotFound); expectedException = "System.NotSupportedException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: Path contains a colon character (:) that is not part of a drive label (C:\\).", expectedException); string invalidPath = SysDrive + @"\dev\test\aaa:aaa.txt"; if (!isLocal) invalidPath = Path.LocalToUnc(invalidPath) + ":aaa.txt"; Directory.CreateDirectory(invalidPath); } catch (NotSupportedException ex) { // win32Error is always 0 for local. if (!isLocal) { var win32Error = new Win32Exception("", ex); Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); } exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // NotSupportedException Console.WriteLine("\nInput Directory Path: [{0}]", tempPath); System.IO.DirectoryInfo dirInfoSysIo = new System.IO.DirectoryInfo(tempPath); DirectoryInfo dirInfo = new DirectoryInfo(tempPath); Assert.AreEqual(dirInfoSysIo.Exists, dirInfo.Exists, "Exists AlphaFS != System.IO"); // Should be false. Assert.IsFalse(dirInfoSysIo.Exists, "System.IO Directory should not exist: [{0}]", tempPath); Assert.IsFalse(dirInfo.Exists, "AlphaFS Directory should not exist: [{0}]", tempPath); StopWatcher(true); dirInfo.Create(true); // Create compressed directory. // dirInfo.Exists should be false. Assert.AreEqual(dirInfoSysIo.Exists, dirInfo.Exists, "AlphaFS Exists should match System.IO"); string root = Path.Combine(tempPath, "Another Sub Directory"); // MAX_PATH hit the road. for (int i = 0; i < level; i++) root = Path.Combine(root, "-" + (i + 1) + "-subdir"); StopWatcher(true); dirInfo = Directory.CreateDirectory(root); report = Reporter(); Console.WriteLine("\n\tCreated directory structure (Should be True): [{0}]{1}", dirInfo.Exists, report); Console.WriteLine("\n\tSubdirectory depth: [{0}], path length: [{1}] characters.", level, root.Length); Assert.IsTrue(Directory.Exists(root), "Directory should exist."); bool compressed = (dirInfo.Attributes & FileAttributes.Compressed) != 0; Console.WriteLine("\n\tCreated compressed directory (Should be True): [{0}]\n", compressed); Assert.IsTrue(compressed, "Directory should be compressed."); } finally { if (Directory.Exists(tempPath, PathFormat.FullPath)) { StopWatcher(true); Directory.Delete(tempPath, true, true); report = Reporter(); exist = Directory.Exists(tempPath); Console.WriteLine("\nDirectory.Delete() (Should be True): [{0}]{1}", !exist, report); Assert.IsFalse(exist, "Cleanup failed: Directory should have been removed."); } } Console.WriteLine(); }
public void SetAccessControl() { Console.WriteLine("Directory.SetAccessControl()"); //string path = SysDrive + @"\AlphaDirectory-" + Path.GetRandomFileName(); string path = Path.Combine(Path.GetTempPath(), "Directory.GetAccessControl()-" + Path.GetRandomFileName()); string pathAlpha = path; Directory.CreateDirectory(path); Console.WriteLine("\n\tDirectory: [{0}]", path); // Initial read. Console.WriteLine("\n\tInitial read."); DirectorySecurity dsAlpha = Directory.GetAccessControl(pathAlpha, AccessControlSections.Access); DirectorySecurity dsSystem = System.IO.Directory.GetAccessControl(path, AccessControlSections.Access); AuthorizationRuleCollection accessRulesSystem = dsSystem.GetAccessRules(true, true, typeof(NTAccount)); StopWatcher(true); AuthorizationRuleCollection accessRulesAlpha = dsAlpha.GetAccessRules(true, true, typeof(NTAccount)); Console.WriteLine("\t\tDirectory.GetAccessControl() rules found: [{0}]\n\t{1}", accessRulesAlpha.Count, Reporter()); Assert.AreEqual(accessRulesSystem.Count, accessRulesAlpha.Count); // Sanity check. DumpAccessRules(1, dsSystem, dsAlpha); // Remove inherited properties. // Passing true for first parameter protects the new permission from inheritance, and second parameter removes the existing inherited permissions. Console.WriteLine("\n\tRemove inherited properties and persist it."); dsAlpha.SetAccessRuleProtection(true, false); // Re-read, using instance methods. System.IO.DirectoryInfo diSystem = new System.IO.DirectoryInfo(Path.LocalToUnc(path)); DirectoryInfo diAlpha = new DirectoryInfo(Path.LocalToUnc(path)); dsSystem = diSystem.GetAccessControl(AccessControlSections.Access); dsAlpha = diAlpha.GetAccessControl(AccessControlSections.Access); // Sanity check. DumpAccessRules(2, dsSystem, dsAlpha); // Restore inherited properties. Console.WriteLine("\n\tRestore inherited properties and persist it."); dsAlpha.SetAccessRuleProtection(false, true); // Re-read. dsSystem = System.IO.Directory.GetAccessControl(path, AccessControlSections.Access); dsAlpha = Directory.GetAccessControl(pathAlpha, AccessControlSections.Access); // Sanity check. DumpAccessRules(3, dsSystem, dsAlpha); diAlpha.Delete(); diAlpha.Refresh(); // Must Refresh() to get actual state. Assert.IsFalse(diAlpha.Exists); }