/// <summary> /// Creates an access template file. /// </summary> internal static void CreateFile(string filePath, params WellKnownSidType[] sids) { File.WriteAllText(filePath, String.Empty); FileInfo info = new FileInfo(filePath); FileSecurity security = info.GetAccessControl(System.Security.AccessControl.AccessControlSections.Access); foreach (FileSystemAccessRule target in security.GetAccessRules(true, true, typeof(NTAccount))) { security.RemoveAccessRule(target); } security.SetAccessRuleProtection(true, false); FileSystemAccessRule rule = new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount)), FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow); security.AddAccessRule(rule); if (sids != null) { foreach (WellKnownSidType sid in sids) { try { rule = new FileSystemAccessRule( new SecurityIdentifier(sid, null).Translate(typeof(NTAccount)), FileSystemRights.ReadAndExecute, InheritanceFlags.None, PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow); security.AddAccessRule(rule); } catch (Exception e) { Utils.Trace((int)Utils.TraceMasks.Error, "Could not translate SID '{0}': {1}", sid, e.Message); } } } info.SetAccessControl(security); }
static public bool SkipUacEnable(bool is_enable) { try { TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler(); service.Connect(); ITaskFolder folder = service.GetFolder(@"\"); // root if (is_enable) { string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location; ITaskDefinition task = service.NewTask(0); task.RegistrationInfo.Author = "WuMgr"; task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST; task.Settings.AllowHardTerminate = false; task.Settings.StartWhenAvailable = false; task.Settings.DisallowStartIfOnBatteries = false; task.Settings.StopIfGoingOnBatteries = false; task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_PARALLEL; task.Settings.ExecutionTimeLimit = "PT0S"; IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = exePath; action.WorkingDirectory = appPath; action.Arguments = "-NoUAC $(Arg0)"; IRegisteredTask registered_task = folder.RegisterTaskDefinition(nTaskName, task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN); if (registered_task == null) { return(false); } // Note: if we run as UWP we need to adjust the file permissions for this workaround to work if (MiscFunc.IsRunningAsUwp()) { if (!FileOps.TakeOwn(exePath)) { return(false); } FileSecurity ac = File.GetAccessControl(exePath); ac.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(FileOps.SID_Worls), FileSystemRights.ReadAndExecute, AccessControlType.Allow)); File.SetAccessControl(exePath, ac); } } else { folder.DeleteTask(nTaskName, 0); } } catch (Exception err) { AppLog.Line("Enable SkipUAC Error {0}", err.ToString()); return(false); } return(true); }
/// <summary> /// Adds an ACL entry on the specified file for the specified account. /// </summary> /// <param name="file">The file to change permissions.</param> /// <param name="account">Reference to the user account.</param> /// <param name="rights">The type of operation associated with the access rule.</param> /// <param name="controlType">Allow or Deny access.</param> private void AddFileSecurity(FileInfo file, IdentityReference account, FileSystemRights rights, AccessControlType controlType) { FileSecurity fSecurity = file.GetAccessControl(); fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType)); file.SetAccessControl(fSecurity); }
public static void applyAppPackages(string file) { FileInfo fInfo = new FileInfo(file); FileSecurity fSecurity = fInfo.GetAccessControl(); fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier("S-1-15-2-1"), FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow)); fInfo.SetAccessControl(fSecurity); }
public static void applyAppPackages(string DLLPath) { FileInfo InfoFile = new FileInfo(DLLPath); FileSecurity fSecurity = File.GetAccessControl("ClientBase.dll"); fSecurity.AddAccessRule(new FileSystemAccessRule("ALL APPLICATION PACKAGES", FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAccessControl("ClientBase.dll", fSecurity); }
public static void GrantEveryoneFullControlAccess(string filePath) { FileInfo fileInfo = new FileInfo(filePath); FileSecurity fSecurity = fileInfo.GetAccessControl(); fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow)); fileInfo.SetAccessControl(fSecurity); }
/// <summary> /// Adds an ACL entry on the specified file for the specified account. /// </summary> /// <param name="fileName"></param> /// <param name="account"></param> /// <param name="rights"></param> /// <param name="controlType"></param> public static void AddFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) { FileInfo fileInfo = new FileInfo(fileName); FileSecurity fileSecurity = fileInfo.GetAccessControl(); fileSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType)); fileInfo.SetAccessControl(fileSecurity); }
public static void SetReadAllUsers(string fileName) { FileSecurity fSecurity = File.GetAccessControl(fileName); fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.ReadData, AccessControlType.Allow)); File.SetAccessControl(fileName, fSecurity); }
/// <summary> /// 授权 /// </summary> /// <param name="path"></param> private static void SetFullControl(string path) { FileInfo info = new FileInfo(path); FileSecurity fs = info.GetAccessControl(); fs.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow)); info.SetAccessControl(fs); }
private static FileSecurity GetSecuritySettings() { FileSecurity fileSecurity = new FileSecurity(); fileSecurity.SetAccessRuleProtection(true, false); fileSecurity.AddAccessRule((FileSystemAccessRule)fileSecurity.AccessRuleFactory((IdentityReference) new NTAccount(WindowsIdentity.GetCurrent().Name), -1, false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow)); return(fileSecurity); }
public static void AddFileSecurity(this FileInfo info, IdentityReference account, FileSystemRights rights, AccessControlType controlType) { FileSecurity fSecurity = info.GetAccessControl(); fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType)); info.SetAccessControl(fSecurity); }
private static void SetAccessRuleOnCSPKeyViaKeyContainer(RSACryptoServiceProvider cspKey, string accountName, CryptoKeyRights keyAccessMask) { #if !NETCOREAPP2_1 throw new InvalidOperationException("incorrect invocation: cannot call this function on non-netcore frameworks."); #else // If we're here, access is granted directly to the file corresponding to the private key. Assuming // this is a machine key (enforced in the calling function), the path to the key container is: // // $env:ProgramData\Microsoft\Crypto\RSA\MachineKeys\<key container unique name> // // e.g.: c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\7e426a4e8a1b8c02e1105b9d7b8c056c_8c9bdc00-1bd7-4654-8e9b-8a234a4b3f88 var keyCtrUniqueName = cspKey.CspKeyContainerInfo.UniqueKeyContainerName; var programDataPath = Environment.GetEnvironmentVariable("ProgramData"); // unlikely to be missing var rsaMachineKeyPath = "Microsoft\\Crypto\\RSA\\MachineKeys"; var keyContainerPath = String.Format($"{programDataPath}\\{rsaMachineKeyPath}\\{keyCtrUniqueName}"); // assert the file exists if (!File.Exists(keyContainerPath)) // odd situation { throw new ArgumentException($"the expected key container file '{keyContainerPath}' does not exist; was it ephemeral or just deleted?"); } try { // extract the current ACL var fileACL = new FileSecurity(keyContainerPath, AccessControlSections.Access); FileSystemRights fileSystemKeyAccessRights = FileAccessRightsFromKeySecurityAccessRights(keyAccessMask); // add the access rule (OS merges) fileACL.AddAccessRule(new FileSystemAccessRule(accountName, fileSystemKeyAccessRights, AccessControlType.Allow)); // put back new FileInfo(keyContainerPath) .SetAccessControl(fileACL); } catch (Exception ex) { Console.WriteLine($"exception encountered trying to access the key container '{keyContainerPath}': {ex.Message} ({ex.HResult})"); } // quick check Console.WriteLine("checking permissions.."); var rules = new FileSecurity(keyContainerPath, AccessControlSections.Access) .GetAccessRules( includeExplicit: true, includeInherited: false, targetType: typeof(System.Security.Principal.NTAccount)); foreach (AuthorizationRule rule in rules) { if (rule is FileSystemAccessRule face) { Console.WriteLine($"ACE: {face.IdentityReference.ToString()}: {face.FileSystemRights.ToString()}"); } } #endif }
public void SetFileSecurity(string path, string dn, string un, bool _lock) { string s = Environment.UserName; FileInfo fi = new FileInfo(path); FileSecurity fs = fi.GetAccessControl(); if (_lock) { originalPermissions = new List <FileSystemAccessRule>(); fs.SetAccessRuleProtection(true, false); AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(NTAccount)); foreach (FileSystemAccessRule rule in rules) { originalPermissions.Add(rule); fs.RemoveAccessRule(rule); } fs.AddAccessRule(new FileSystemAccessRule(dn + "\\" + un, FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAccessControl(path, fs); } else { if (!(held.Count < 1)) { foreach (object[] o in held) { if ((string)o[0] == path) { JArray j = (JArray)o[2]; List <FileSystemAccessRule> l = j.ToObject <List <FileSystemAccessRule> >(); if (l == null || l.Count < 1) { break; } foreach (FileSystemAccessRule p in (List <FileSystemAccessRule>)o[2]) { fs.AddAccessRule(p); } break; } } } fs.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAccessControl(path, fs); } }
public static void SetPermission(List <string> sharedList, string filePath) { try { FileInfo info = new FileInfo(filePath); FileSecurity fs = info.GetAccessControl(); /* Start of Take Ownership by Cato Yeung 2016/04/10 */ //SecurityIdentifier cu = WindowsIdentity.GetCurrent().User; //fs.SetOwner(cu); //File.SetAccessControl(filePath, fs); /* End of Take Ownership by Cato Yeung 2016/04/10 */ fs.SetAccessRuleProtection(true, false); fs.AddAccessRule(new FileSystemAccessRule(@"kmhk\itadmin", FileSystemRights.FullControl, AccessControlType.Allow)); fs.AddAccessRule(new FileSystemAccessRule(AdUtil.GetUserIdByUsername(GlobalService.User, "kmhk.local"), FileSystemRights.FullControl, AccessControlType.Allow)); foreach (string shared in sharedList) { string staffId = AdUtil.GetUserIdByUsername(shared.Trim(), "kmhk.local"); //Debug.WriteLine(shared + " " + filePath); //fs.SetAccessRuleProtection(true, false); fs.AddAccessRule(new FileSystemAccessRule(staffId, FileSystemRights.Modify, AccessControlType.Allow)); if (UserUtil.IsSpecialUser(shared)) //if (shared == "Chow Chi To(周志滔,Sammy)" || shared == "Ling Wai Man(凌慧敏,Velma)" || shared == "Chan Fai Lung(陳輝龍,Onyx)" || shared == "Ng Lau Yu, Lilith (吳柳如)" || // shared == "Lee Miu Wah(李苗華)" || shared == "Lee Ming Fung(李銘峯)" || shared == "Ho Kin Hang(何健恒,Ken)" || shared == "Yeung Wai, Gabriel (楊偉)") { string asText = string.Format("select as_userid from TB_USER_AS where as_user = N'{0}'", shared.Trim()); string asId = DataService.GetInstance().ExecuteScalar(asText).ToString().Trim(); fs.AddAccessRule(new FileSystemAccessRule(asId, FileSystemRights.Modify, AccessControlType.Allow)); } } File.SetAccessControl(filePath, fs); } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); MessageBox.Show("Errors found when setting permission."); } }
public static void SetReadAccessOnDefinitionFile(string definitionName, string user) { string filePathName = ScheduledJobStore.GetFilePathName(definitionName, "ScheduledJobDefinition"); FileSecurity fileSecurity = new FileSecurity(filePathName, AccessControlSections.Access); FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(user, FileSystemRights.Read, AccessControlType.Allow); fileSecurity.AddAccessRule(fileSystemAccessRule); File.SetAccessControl(filePathName, fileSecurity); }
public static void AddAcl(string fileName, IdentityReference sid) { var file = new FileInfo(fileName); FileSecurity fs = file.GetAccessControl(); fs.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.Read, AccessControlType.Allow)); file.SetAccessControl(fs); }
static SimpleFile() { _defaultSecurity = new FileSecurity(); _defaultSecurity.AddAccessRule( new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); }
private FileSecurity GetFileSecurity(FileSystemRights rights) { var security = new FileSecurity(); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new FileSystemAccessRule(identity, rights, AccessControlType.Allow); security.AddAccessRule(accessRule); return(security); }
public static FileSecurity CreateFileSecurity(string[] identities) { System.Security.AccessControl.FileSecurity fileSecurity = new FileSecurity(); foreach (var item in identities) { fileSecurity.AddAccessRule(new FileSystemAccessRule(item, FileSystemRights.FullControl, AccessControlType.Allow)); } return(fileSecurity); }
public static void GetFullAccess(string path) { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); IdentityReference act = sid.Translate(typeof(NTAccount)); FileSecurity sec = File.GetAccessControl(path); sec.AddAccessRule(new FileSystemAccessRule(act, FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAccessControl(path, sec); }
private static void makeLogFileWritable() { FileSecurity fileSecurity = File.GetAccessControl(Prefs.LogFilepath); fileSecurity.AddAccessRule(new FileSystemAccessRule( "Users", FileSystemRights.Write, AccessControlType.Allow)); File.SetAccessControl(Prefs.LogFilepath, fileSecurity); }
/* Good1() changes PRIVATE_CONST_TRUE to PRIVATE_CONST_FALSE */ private void Good1() { if (PRIVATE_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); } else { /* FIX: Create a file without excessive privileges */ string user = Environment.UserDomainName + "\\" + Environment.UserName; string path = @"C:\Temp\WriteText.txt"; FileSecurity fSecurity = new FileSecurity(); fSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Read, AccessControlType.Allow)); fSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Write, AccessControlType.Deny)); File.Create(path, 1024, FileOptions.WriteThrough, fSecurity); } }
static void ReplacePermissions(string filepath, WellKnownSidType sidType, FileSystemRights allow) { FileSecurity sec = File.GetAccessControl(filepath); SecurityIdentifier sid = new SecurityIdentifier(sidType, null); sec.PurgeAccessRules(sid); //remove existing sec.AddAccessRule(new FileSystemAccessRule(sid, allow, AccessControlType.Allow)); File.SetAccessControl(filepath, sec); }
public static void Main() { try { // Create a file and write data to it. // Create an array of bytes. byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data."); // Specify an access control list (ACL) FileSecurity fs = new FileSecurity(); fs.AddAccessRule(new FileSystemAccessRule(@"DOMAINNAME\AccountName", FileSystemRights.ReadData, AccessControlType.Allow)); // Create a file using the FileStream class. FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs); // Write the number of bytes to the file. fWrite.WriteByte((byte)messageByte.Length); // Write the bytes to the file. fWrite.Write(messageByte, 0, messageByte.Length); // Close the stream. fWrite.Close(); // Open a file and read the number of bytes. FileStream fRead = new FileStream("test.txt", FileMode.Open); // The first byte is the string length. int length = (int)fRead.ReadByte(); // Create a new byte array for the data. byte[] readBytes = new byte[length]; // Read the data from the file. fRead.Read(readBytes, 0, readBytes.Length); // Close the stream. fRead.Close(); // Display the data. Console.WriteLine(Encoding.ASCII.GetString(readBytes)); Console.WriteLine("Done writing and reading data."); } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); }
protected override void OnBeforeInstall(IDictionary savedState) { string targetPath = string.Empty; StringDictionary myStringDictionary = Context.Parameters; foreach (string param in myStringDictionary.Keys) { var paramToLower = param.ToLower(); if (paramToLower.Contains("assemblypath")) { var fileInfo = new FileInfo(myStringDictionary[param]); targetPath = fileInfo.DirectoryName; } } if (!string.IsNullOrEmpty(targetPath)) { var applicationSettingsPath = Path.Combine(targetPath, "Settings"); var licensePath = Path.Combine(applicationSettingsPath, "Licenses.dat"); var licenseFound = false; if (!Directory.Exists(applicationSettingsPath)) { Directory.CreateDirectory(applicationSettingsPath); //when file does not exists create trial license Atum.DAL.Licenses.OnlineCatalogLicenses.CreateTrialLicense(licensePath); } else { licenseFound = File.Exists(Atum.DAL.ApplicationSettings.Settings.LocalLicenseFilePath); } //change permissions on license.dat so every user can change it try { if (File.Exists(licensePath)) { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); FileSystemAccessRule writerule = new FileSystemAccessRule(sid, FileSystemRights.Modify, AccessControlType.Allow); // Get your file's ACL FileSecurity fileSecurity = File.GetAccessControl(licensePath); // Add the new rule to the ACL fileSecurity.AddAccessRule(writerule); // Set the ACL back to the file File.SetAccessControl(licensePath, fileSecurity); } } catch (Exception exc) { } } base.OnBeforeInstall(savedState); }
public static void EnsureLoaderPermissions(string path) { var fs = new FileSecurity(); fs.SetAccessRuleProtection(true, false); fs.AddAccessRule( new FileSystemAccessRule( WindowsIdentity.GetCurrent().Name, FileSystemRights.FullControl, AccessControlType.Allow)); fs.AddAccessRule( new FileSystemAccessRule( "BUILTIN\\Administrators", FileSystemRights.Delete, AccessControlType.Allow)); File.SetAccessControl(path, fs); }
private static bool SetFileAccess(string user, string filePath) { System.IO.FileInfo fileInfo = new FileInfo(filePath); FileSecurity fs = fileInfo.GetAccessControl(); fs.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Modify, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow)); fileInfo.SetAccessControl(fs); return(true); }
public override void Bad() { if (IO.StaticReturnsTrueOrFalse()) { /* FLAW: Create a file with excessive privileges */ string path = @"C:\Temp\WriteText.txt"; File.Create(path); } else { /* FIX: Create a file without excessive privileges */ string user = Environment.UserDomainName + "\\" + Environment.UserName; string path = @"C:\Temp\WriteText.txt"; FileSecurity fSecurity = new FileSecurity(); fSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Read, AccessControlType.Allow)); fSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Write, AccessControlType.Deny)); File.Create(path, 1024, FileOptions.WriteThrough, fSecurity); } }
public override void Install(IDictionary savedState) { base.Install(savedState); // Create .dat file // // NOTE: during install we can't access the Web.config file, so the file name // is just hard-coded here. Given that you can't change the web.config file // during install, this really shouldn't be a problem. If someone changes the // file location, then they'll have to deal with the problem of file permissions. // Console.WriteLine("Creating Venue Service data file."); string filepath = InstallPath + @"VenueService.dat"; if (!File.Exists(filepath)) { using (FileStorage file = new FileStorage(filepath)) { // Add two sample venues file.AddVenue(new Venue("*****@*****.**", "234.7.13.19", 5004, "Sample Venue 1", null, null)); file.AddVenue(new Venue("*****@*****.**", "235.8.14.20", 5004, "Sample Venue 2", null, null)); } } else { Console.WriteLine("Data file exists. Skipping creating file."); } // Store the location of the .dat file so the admin tool can find it using (RegistryKey key = Registry.LocalMachine.CreateSubKey(LocalMachineSubkey)) { key.SetValue("DataFile", filepath); } try { FileSecurity fileSec = File.GetAccessControl(filepath); fileSec.AddAccessRule(new FileSystemAccessRule("IUSR_" + Environment.MachineName, FileSystemRights.Modify, AccessControlType.Allow)); File.SetAccessControl(filepath, fileSec); } catch (Exception) { MessageBox.Show( "Setting the file security for the venueservice.dat file failed. \n" + "This may be caused by the Internet Guest Account not being present \n" + "or properly named. \n" + "\nFor Venue Service to work properly, the data file must be \n" + "modifiable by the Internet Guest Account. You must add \"modify\" \n" + "permissions on the file for the Internet Guest Account.", "File Security Changes Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void AccessRuleType_Returns_Valid_Object() { var accessRule = new FileSystemAccessRule(Helpers.s_LocalSystemNTAccount, FileSystemRights.AppendData, AccessControlType.Allow); var fileSecurity = new FileSecurity(); fileSecurity.AddAccessRule(accessRule); Type accessRuleType = fileSecurity.AccessRuleType; Assert.Equal(typeof(FileSystemAccessRule), accessRuleType); }