public override void ExecuteCmdlet() { var PathIO = new System.IO.DirectoryInfo(Path); var SelectedWeb = this.ClientContext.Web; if (string.IsNullOrEmpty(Path) || !PathIO.Exists) { // build the directory structure in the users AppData for file download/upload string result = System.IO.Path.GetTempPath(); var resultdir = new System.IO.DirectoryInfo(result); // create the path/directory and inherit permissions PathIO = resultdir.CreateSubdirectory("iaclogs", resultdir.GetAccessControl()); } // Pull listitem from list var list = List.GetList(SelectedWeb); if (list != null) { // Commented out to demonstrate extension handling URL property initialization // ClientContext.Load(SelectedWeb, wctx => wctx.Url); var item = list.GetItemById(ItemId); ClientContext.Load(item, ictx => ictx.Id, ictx => ictx["Title"], ictx => ictx["FileLeafRef"]); ClientContext.ExecuteQueryRetry(); var filepath = item.DownloadFile(ClientContext, PathIO.FullName); LogVerbose("Successfully downloaded {0}", filepath); } }
internal static bool CheckWriteAccessAndCreate(this System.IO.DirectoryInfo directory, out string errorMessage) { System.IO.DirectoryInfo directoryToCheck = directory.Parent; if (!directoryToCheck.Exists) { errorMessage = "Parent folder doesn't exist."; return(false); } errorMessage = ""; string whoIsTrying = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // Gets all access security types for directory System.Security.AccessControl.DirectorySecurity security; try { security = directoryToCheck.GetAccessControl(System.Security.AccessControl.AccessControlSections.All); } catch (System.Security.AccessControl.PrivilegeNotHeldException e) { errorMessage = e.Message; Tracer.Log($"\"SeSecurityPrivilege\" error: {whoIsTrying} doesn't have privileges to check folder's security ({directoryToCheck})", e); return(false); } // Collects all access rules for that security types System.Security.AccessControl.AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); // Iterate each access rule for (var i = 0; i < rules.Count; i++) { var rule = rules[i]; // Do we match the identity ? if (rule.IdentityReference.Value.Equals(whoIsTrying, System.StringComparison.CurrentCultureIgnoreCase)) { var fsAccessRule = rule as System.Security.AccessControl.FileSystemAccessRule; // cast to check 4 access rights var hasAccessOrNotBordelDeMerde = (fsAccessRule.FileSystemRights & System.Security.AccessControl.FileSystemRights.WriteData) > 0 && fsAccessRule.AccessControlType != System.Security.AccessControl.AccessControlType.Deny; if (!hasAccessOrNotBordelDeMerde) { errorMessage = $"\"{whoIsTrying}\" does not have write access to {directoryToCheck}"; return(false); } try { directory.Create(); } catch (System.Exception e) { errorMessage = e.Message; Tracer.Log($@"Exception in Config.CheckCreate for this folder: ""{directory.ToString()}""", e); return(false); } } } return(true); }
private void Directory_SetAccessControl(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { var folder = tempRoot.CreateDirectory(); var sysIO = System.IO.Directory.GetAccessControl(folder.FullName); var sysIOaccessRules = sysIO.GetAccessRules(true, true, typeof(NTAccount)); var alphaFS = Alphaleonis.Win32.Filesystem.Directory.GetAccessControl(folder.FullName); var alphaFSaccessRules = alphaFS.GetAccessRules(true, true, typeof(NTAccount)); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); Console.WriteLine("\n\tSystem.IO rules found: [{0}]\n\tAlphaFS rules found : [{1}]", sysIOaccessRules.Count, alphaFSaccessRules.Count); Assert.AreEqual(sysIOaccessRules.Count, alphaFSaccessRules.Count); // Sanity check. UnitTestConstants.TestAccessRules(sysIO, alphaFS); // 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."); alphaFS.SetAccessRuleProtection(true, false); Alphaleonis.Win32.Filesystem.Directory.SetAccessControl(folder.FullName, alphaFS, AccessControlSections.Access); // Re-read, using instance methods. var sysIOdi = new System.IO.DirectoryInfo(folder.FullName); var alphaFSdi = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder.FullName); sysIO = sysIOdi.GetAccessControl(AccessControlSections.Access); alphaFS = alphaFSdi.GetAccessControl(AccessControlSections.Access); // Sanity check. UnitTestConstants.TestAccessRules(sysIO, alphaFS); // Restore inherited properties. Console.WriteLine("\n\tRestore inherited properties and persist it."); alphaFS.SetAccessRuleProtection(false, true); Alphaleonis.Win32.Filesystem.Directory.SetAccessControl(folder.FullName, alphaFS, AccessControlSections.Access); // Re-read. sysIO = System.IO.Directory.GetAccessControl(folder.FullName, AccessControlSections.Access); alphaFS = Alphaleonis.Win32.Filesystem.Directory.GetAccessControl(folder.FullName, AccessControlSections.Access); // Sanity check. UnitTestConstants.TestAccessRules(sysIO, alphaFS); } Console.WriteLine(); }
public static void FolderDenyPermission(bool create, string tempPath) { var user = (Environment.UserDomainName + @"\" + Environment.UserName).TrimStart('\\'); var dirInfo = new System.IO.DirectoryInfo(tempPath); System.Security.AccessControl.DirectorySecurity dirSecurity; // ╔═════════════╦═════════════╦═══════════════════════════════╦════════════════════════╦══════════════════╦═══════════════════════╦═════════════╦═════════════╗ // ║ ║ folder only ║ folder, sub-folders and files ║ folder and sub-folders ║ folder and files ║ sub-folders and files ║ sub-folders ║ files ║ // ╠═════════════╬═════════════╬═══════════════════════════════╬════════════════════════╬══════════════════╬═══════════════════════╬═════════════╬═════════════╣ // ║ Propagation ║ none ║ none ║ none ║ none ║ InheritOnly ║ InheritOnly ║ InheritOnly ║ // ║ Inheritance ║ none ║ Container|Object ║ Container ║ Object ║ Container|Object ║ Container ║ Object ║ // ╚═════════════╩═════════════╩═══════════════════════════════╩════════════════════════╩══════════════════╩═══════════════════════╩═════════════╩═════════════╝ var rule = new System.Security.AccessControl.FileSystemAccessRule(user, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit | System.Security.AccessControl.InheritanceFlags.ObjectInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Deny); if (create) { dirInfo.Create(); // Set DENY for current user. dirSecurity = dirInfo.GetAccessControl(); dirSecurity.AddAccessRule(rule); dirInfo.SetAccessControl(dirSecurity); } else { // Remove DENY for current user. dirSecurity = dirInfo.GetAccessControl(); dirSecurity.RemoveAccessRule(rule); dirInfo.SetAccessControl(dirSecurity); } }
static StackObject *GetAccessControl_21(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.IO.DirectoryInfo instance_of_this_method = (System.IO.DirectoryInfo) typeof(System.IO.DirectoryInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetAccessControl(); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
internal System.IO.FileInfo FullDocumentPath(string targetLocation, string partialUrl, string fileName) { var local = new System.IO.DirectoryInfo(targetLocation); local = local.CreateSubdirectory("FileStream"); foreach (var partial in partialUrl.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)) { local = local.CreateSubdirectory(partial, local.GetAccessControl()); } var localfile = new System.IO.FileInfo(string.Format("{0}\\{1}", local.FullName, fileName)); return(localfile); }
private void SetSecuritySystem(string directory) { 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")); var testDirInfo = new System.IO.DirectoryInfo(directory); var ds = testDirInfo.GetAccessControl(System.Security.AccessControl.AccessControlSections.Access); ds.SetAccessRuleProtection(true, false); ds.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null), System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit | System.Security.AccessControl.InheritanceFlags.ObjectInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow)); testDirInfo.SetAccessControl(ds); }
private void Form1_Load(object sender, EventArgs e) { SetStatusOfStructureForms(true); currentTT = new Timetable(); undoStack = new Stack<undoRedoEvent>(); redoStack = new Stack<undoRedoEvent>(); //get command line arguments. string[] args = Environment.GetCommandLineArgs(); if (args.Length > 1) { currentTT.Load(args[1]); return; } string appPath = AppDomain.CurrentDomain.BaseDirectory; //before we can write to the directory, we MUST set permissions, so that we are able to write to the Program Files area of the hard drive. //Failing to do this will result in the program crashing if not being 'Run as Adminstrator'. System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(appPath); DirectorySecurity security = dInfo.GetAccessControl(); security.SetAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow)); dInfo.SetAccessControl(security); if (!System.IO.File.Exists(appPath + "normal.TTT")) { System.IO.File.WriteAllBytes(appPath + "normal.TTT", TimeLord.Properties.Resources.Template); //write the contents of the TimeLord Standard template to the drive, if not found. MessageBox.Show("No default template has been created. The pre-designed template will therefore be used.","No Template"); } currentTT.Load(appPath + "normal.TTT"); //load the standard template in. NB: Creating a new timetable will clear this template. }
private void Directory_SetAccessControl(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); var tempPath = System.IO.Path.GetTempPath(); if (isNetwork) { tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); } using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { var folder = rootDir.RandomDirectoryFullPath; System.IO.Directory.CreateDirectory(folder); var sysIO = System.IO.Directory.GetAccessControl(folder); var sysIOaccessRules = sysIO.GetAccessRules(true, true, typeof(NTAccount)); var alphaFS = Alphaleonis.Win32.Filesystem.Directory.GetAccessControl(folder); var alphaFSaccessRules = alphaFS.GetAccessRules(true, true, typeof(NTAccount)); Console.WriteLine("\nInput Directory Path: [{0}]", folder); Console.WriteLine("\n\tSystem.IO rules found: [{0}]\n\tAlphaFS rules found : [{1}]", sysIOaccessRules.Count, alphaFSaccessRules.Count); Assert.AreEqual(sysIOaccessRules.Count, alphaFSaccessRules.Count); // Sanity check. UnitTestConstants.TestAccessRules(sysIO, alphaFS); // 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."); alphaFS.SetAccessRuleProtection(true, false); Alphaleonis.Win32.Filesystem.Directory.SetAccessControl(folder, alphaFS, AccessControlSections.Access); // Re-read, using instance methods. var sysIOdi = new System.IO.DirectoryInfo(folder); var alphaFSdi = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder); sysIO = sysIOdi.GetAccessControl(AccessControlSections.Access); alphaFS = alphaFSdi.GetAccessControl(AccessControlSections.Access); // Sanity check. UnitTestConstants.TestAccessRules(sysIO, alphaFS); // Restore inherited properties. Console.WriteLine("\n\tRestore inherited properties and persist it."); alphaFS.SetAccessRuleProtection(false, true); Alphaleonis.Win32.Filesystem.Directory.SetAccessControl(folder, alphaFS, AccessControlSections.Access); // Re-read. sysIO = System.IO.Directory.GetAccessControl(folder, AccessControlSections.Access); alphaFS = Alphaleonis.Win32.Filesystem.Directory.GetAccessControl(folder, AccessControlSections.Access); // Sanity check. UnitTestConstants.TestAccessRules(sysIO, alphaFS); } Console.WriteLine(); }
public System.Security.AccessControl.DirectorySecurity GetAccessControl() { return(inner.GetAccessControl()); }
private void btnSubmit_Click(object sender, EventArgs e) { string dC = Convert.ToString(tbDC.Text); //get the DC in order to be able to connect string oU = Convert.ToString(tbOU.Text); //Add "OU=" to the string so DirectoryServices can search for the OU needed string lDAP = "LDAP://" + dC + ":389/" + oU; //LDAP string needed for the OU where the security groups will be created string filePath = Convert.ToString(tbFilePath.Text); //convert the filepath provided to a user string groupBase = filePath.Replace(@"\\", ""); //get the group base name to be used to create security groups in AD string groupBaseStr = null; if (groupBase.Length < 55) { groupBaseStr = groupBase; } else if (groupBase.Length > 55) { int groupBaseLength = groupBase.Length; int lengthDif = groupBaseLength - 56; string tempGroupBase = groupBase.Remove(0, lengthDif); string newGroupBase = tempGroupBase.Insert(0, "%"); groupBaseStr = newGroupBase; } //check the number of characters in the group base name. If it is too many characters, remove the excess characters and add in a % to indicate to the Tech that this has been done. string groupBaseName = groupBaseStr.Replace('\\', '.'); //the base group name that will be used in AD for security groups string groupWrite = groupBaseName + (@" - W"); //the write permission security group string groupWriteCN = "CN=" + Convert.ToString(groupWrite); //Add "CN=" so Directory Services can create the group in the specified OU string groupRead = groupBaseName + (@" - R"); //the read permission security group string groupReadCN = "CN=" + Convert.ToString(groupRead); //Add "CN=" so Directory Services can create the group in the specified OU DirectoryEntry aclOu = new DirectoryEntry("LDAP://" + dC + ":389/" + oU); DirectoryEntry groupW = aclOu.Children.Add(groupWriteCN, "group"); groupW.Properties["samAccountName"].Value = groupWrite; groupW.CommitChanges(); //Create Write Security Group in AD DirectoryEntry groupR = aclOu.Children.Add(groupReadCN, "group"); groupR.Properties["samAccountName"].Value = groupRead; groupR.CommitChanges(); //Create Read Security Group in AD System.Threading.Thread.Sleep(60000); //wait to let the creation of the groups propogate to other DCs. System.IO.DirectoryInfo folderInfo = new System.IO.DirectoryInfo(filePath); DirectorySecurity folderSecurity = folderInfo.GetAccessControl(); FileSystemAccessRule ruleR = new FileSystemAccessRule(groupRead, FileSystemRights.Read | FileSystemRights.ReadAndExecute | FileSystemRights.ListDirectory, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); folderSecurity.AddAccessRule(ruleR); folderInfo.SetAccessControl(folderSecurity); //Assign Read permissions on the folder for the Read Security Group FileSystemAccessRule ruleW = new FileSystemAccessRule(groupWrite, FileSystemRights.Modify | FileSystemRights.Read | FileSystemRights.ReadAndExecute | FileSystemRights.ListDirectory | FileSystemRights.Write, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); folderSecurity.AddAccessRule(ruleW); folderInfo.SetAccessControl(folderSecurity); //Assign Write permissions on the folder for the Write Security Group if (cBoxTraverse.Checked) { ListDirectories pathsList = new ListDirectories(); //call DirectoryHelper class to create the list of the parent file pathes List <string> parentPaths = pathsList.GetDirectories(filePath); parentPaths.RemoveAt(0); //removes the filePath (the full path provided) from the list as it should not receive list permissions foreach (string p in parentPaths) { System.IO.DirectoryInfo folderInfoLR = new System.IO.DirectoryInfo(p); DirectorySecurity folderSecurityLR = folderInfoLR.GetAccessControl(); FileSystemAccessRule ruleLR = new FileSystemAccessRule(groupRead, FileSystemRights.Traverse | FileSystemRights.ListDirectory | FileSystemRights.ReadAttributes | FileSystemRights.ReadExtendedAttributes | FileSystemRights.ReadPermissions, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow); folderSecurityLR.AddAccessRule(ruleLR); folderInfoLR.SetAccessControl(folderSecurityLR); System.IO.DirectoryInfo folderInfoLW = new System.IO.DirectoryInfo(p); DirectorySecurity folderSecurityLW = folderInfoLW.GetAccessControl(); FileSystemAccessRule ruleLW = new FileSystemAccessRule(groupWrite, FileSystemRights.Traverse | FileSystemRights.ListDirectory | FileSystemRights.ReadAttributes | FileSystemRights.ReadExtendedAttributes | FileSystemRights.ReadPermissions, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow); folderSecurityLW.AddAccessRule(ruleLW); folderInfoLW.SetAccessControl(folderSecurityLW); //assigning list/traverse permissions to parent folders, so that groups can get into the folder. } } }
/// <summary> /// Process the request /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); LogVerbose("Now migrating attachments from list to library {0}.", this.DestinationLibraryName); var result = System.IO.Path.GetTempPath(); var resultdir = new System.IO.DirectoryInfo(result); _resultLogDirectory = resultdir.CreateSubdirectory("downloadedAttachments", resultdir.GetAccessControl()); List _srclist = this.ClientContext.Web.Lists.GetByTitle(SourceListName); Folder _rootFolder = _srclist.RootFolder; this.ClientContext.Load(_srclist); this.ClientContext.Load(_rootFolder); this.ClientContext.ExecuteQuery(); List _dlist = this.ClientContext.Web.Lists.GetByTitle(DestinationLibraryName); Folder _drootFolder = _dlist.RootFolder; this.ClientContext.Load(_dlist); this.ClientContext.Load(_drootFolder); this.ClientContext.ExecuteQuery(); LogVerbose("Source List {0} with root folder {1}", _srclist.Title, _rootFolder.ServerRelativeUrl); LogVerbose("Destination List {0} with root folder {1}", _dlist.Title, _drootFolder.ServerRelativeUrl); //check if list is discussion list bool _isDiscussionList = false; ContentTypeCollection contentTypeColl = _srclist.ContentTypes; this.ClientContext.Load(contentTypeColl); this.ClientContext.ExecuteQuery(); LogVerbose("Checking Content types:"); foreach (ContentType contentType in contentTypeColl) { if (contentType.Name.IndexOf("Discussion") > -1) { LogVerbose("Name: {0} Id: {1}", contentType.Name, contentType.Id); _isDiscussionList = true; break; } } if (!(String.IsNullOrEmpty(StartingFolder))) { //Create StartingFolder _dlist.RootFolder.Folders.Add(StartingFolder); _dlist.Update(); this.ClientContext.ExecuteQuery(); } if (SiteAction.Equals("copy-files", StringComparison.CurrentCultureIgnoreCase)) { //Process items for attachement GetItemsWithinFolder(_srclist, _dlist, _srclist.RootFolder); } if (!_isDiscussionList) { FolderCollection _folders = _rootFolder.Folders; this.ClientContext.Load(_folders); this.ClientContext.ExecuteQuery(); foreach (Folder _folder in _folders) { LogVerbose(">>>> {0}", _folder.Name); if ((_folder.Name != "Attachments") && (_folder.Name != "Item")) { LogVerbose(">>>>" + _folder.Name); ProcessFolder(_folder, _srclist, _dlist); } } } }
/// <summary> /// Retreive the folder or create the directory /// </summary> /// <param name="rootDir"></param> /// <param name="folderName"></param> /// <returns></returns> public static string GetOrCreateDirectory(this System.IO.DirectoryInfo rootDir, string folderName) { var outputPathDir = string.Empty; var pathContent = System.IO.Path.Combine(rootDir.FullName, folderName); if (!System.IO.Directory.Exists(pathContent)) { var outputInfoPathDir = System.IO.Directory.CreateDirectory(pathContent, rootDir.GetAccessControl()); outputPathDir = outputInfoPathDir.FullName; System.Diagnostics.Trace.TraceInformation("Directory {0} created", outputPathDir); } else { var outputInfoPathDir = new System.IO.DirectoryInfo(pathContent); outputPathDir = outputInfoPathDir.FullName; System.Diagnostics.Trace.TraceInformation("Directory {0} found", outputPathDir); } return(outputPathDir); }