//} // Method borrowed from StackOverflow // (https://stackoverflow.com/questions/130617/how-do-you-check-for-permissions-to-write-to-a-directory-or-file) private static bool HasWriteAccessToFile(string filePath) { try { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filePath); permissionSet.AddPermission(writePermission); return(permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)); } catch (Exception ex) { return(false); } }
private static bool Check(ISecurityDeclarationProvider caller, ISecurityDeclarationProvider callee) { // 1 - look if the callee has a LinkDemand PermissionSet calleeLinkDemand = GetLinkDemand(callee); if (calleeLinkDemand.Count == 0) { return(true); } // 2 - Ensure the caller requires a superset (or the same) permissions return(calleeLinkDemand.IsSubsetOf(GetLinkDemand(caller))); }
public static bool CanWriteToFile(string filename) { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return(true); } return(false); }
private void CheckPermission() { var folder = ConfigurationManager.AppSettings["AttachmentsDirectory"]; var permission = new FileIOPermission(FileIOPermissionAccess.Write, Server.MapPath(folder)); var permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(permission); if (!permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { WarningLabel.Text = String.Format(CultureInfo.CurrentUICulture, "The directory \"{0}\" is write protected", folder); //AttachmentPanel.Enabled = false; } }
//===== // Generate XML file for a specific app. private void WriteStyleXML(string targetFile, string fgColor, string bgColor) { string xmlPath = Path.GetDirectoryName(targetFile); string xmlFile = Path.GetFileNameWithoutExtension(targetFile) + ".VisualElementsManifest.xml"; string xmlFull = Path.Combine(xmlPath, xmlFile); PermissionSet permissionSet = new PermissionSet(PermissionState.None); FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, xmlFull); //FileIOPermissionAccess.AllAccess permissionSet.AddPermission(writePermission); if (!permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { out2box("Permission denied: " + xmlFull + "\n", "red"); return; } if (System.IO.File.Exists(xmlFull)) { out2box("Already exists: " + xmlFull + "\n", "blue"); return; } try { FileStream fs = new FileStream(xmlFull, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.Flush(); sw.BaseStream.Seek(0, SeekOrigin.Begin); sw.WriteLine("<Application>"); sw.WriteLine(" <VisualElements"); sw.WriteLine(" ShowNameOnSquare150x150Logo='on'"); sw.WriteLine(" ForegroundText='" + fgColor + "'"); sw.WriteLine(" BackgroundColor='#" + bgColor + "'/>"); sw.WriteLine("</Application>"); sw.Flush(); sw.Close(); fs.Close(); out2box("Success: " + xmlFull + "\n", "green"); generatedXMLs.Add(xmlFull); } catch (UnauthorizedAccessException ex) { out2box("Permission denied: " + xmlFull + "\n", "red"); } }
public static bool IsDirectoryWritable(string directory) { if (string.IsNullOrWhiteSpace(directory)) { return(false); } FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, HostingEnvironment.MapPath(directory)); PermissionSet permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(permission); return(permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)); }
/// <summary> /// Checking for directory and file read/write permissions /// </summary> /// <param name="path"></param> /// <returns></returns> public static bool HasAccess(string path, FileIOPermissionAccess access) { PermissionSet permissionSet = new PermissionSet(PermissionState.None); FileIOPermission permission = new FileIOPermission(access, path); permissionSet.AddPermission(permission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return(true); } return(false); }
/// <summary> /// Check whether the current user has write permission to the specified path. /// </summary> /// <param name="path">Absolut path to be checked for permissions</param> /// <returns><c>true</c> if the write permission is granted, otherwise <c>false</c></returns> public static bool HasWritePermissionOnDir(string path) { var writeAllow = false; var writeDeny = false; try { var accessControlList = Directory.GetAccessControl(path); if (accessControlList == null) { return(false); } var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); if (accessRules == null) { return(false); } foreach (System.Security.AccessControl.FileSystemAccessRule rule in accessRules) { if ((System.Security.AccessControl.FileSystemRights.Write & rule.FileSystemRights) != System.Security.AccessControl.FileSystemRights.Write) { continue; } if (rule.AccessControlType == System.Security.AccessControl.AccessControlType.Allow) { writeAllow = true; } else if (rule.AccessControlType == System.Security.AccessControl.AccessControlType.Deny) { writeDeny = true; } } } catch (System.PlatformNotSupportedException) { #if __MonoCS__ writeAllow = (0 == Syscall.access(path, AccessModes.W_OK)); #endif } catch (System.UnauthorizedAccessException) { var permission = new FileIOPermission(FileIOPermissionAccess.Write, path); var permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(permission); return(permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)); } return(writeAllow && !writeDeny); }
private static bool IsCandidateSandbox(AppDomain candidateSandbox, string requiredAppBase, PermissionSet requiredGrantSet, IEnumerable <Assembly> requiredFullTrustList) { Debug.Assert(candidateSandbox != null, "candidateSandbox != null"); Debug.Assert(!String.IsNullOrEmpty(requiredAppBase), "!String.IsNullOrEmpty(requiredAppBase)"); Debug.Assert(requiredGrantSet != null, "requiredGrantSet != null"); // The candidate sandbox must have the correct AppBase if (!String.Equals(candidateSandbox.SetupInformation.ApplicationBase, requiredAppBase, StringComparison.OrdinalIgnoreCase)) { return(false); } // It must have the same grant set PermissionSet candidateGrantSet = candidateSandbox.GetPermissionSet(); if (!requiredGrantSet.IsSubsetOf(candidateGrantSet) || !candidateGrantSet.IsSubsetOf(requiredGrantSet)) { return(false); } // If there is no required full trust list, then the candidate must not have one either IList <StrongName> candidateFullTrustList = candidateSandbox.ApplicationTrust.GetFullTrustAssemblies(); if (requiredFullTrustList == null) { return(candidateFullTrustList.Count == 0); } // If there is a required full trust list, the candidate must have the same number of trusted // assemblies if (requiredFullTrustList.Count() != candidateFullTrustList.Count) { return(false); } // And each assembly in the candidate list must be in the required list if (requiredFullTrustList.Any(a => !candidateFullTrustList.Contains(a.GetStrongName()))) { return(false); } return(true); }
public bool CheckLocationReadable(string path) { var permissionSet = new PermissionSet(PermissionState.None); try { var writePermission = new FileIOPermission(FileIOPermissionAccess.Read, path); permissionSet.AddPermission(writePermission); return(permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)); } catch { return(false); } }
private static bool IsDataObjectFromLessPriviligedApplicationDomain(IDataObject dataObjectToApply) { bool retVal = false; object applicationTrust = null; // Extract the permission set in case of xaml cut and paste // extract permission set if it exists if not data came from full trust app and we do not care bool isApplicationTrustFormatPresent = false; isApplicationTrustFormatPresent = dataObjectToApply.GetDataPresent(DataFormats.ApplicationTrust, /*autoConvert:*/ false); if (isApplicationTrustFormatPresent) { applicationTrust = dataObjectToApply.GetData(DataFormats.ApplicationTrust, /*autoConvert:*/ false); } if (applicationTrust != null) { string applicationTrustText = null; // convert to string applicationTrustText = applicationTrust.ToString(); // Convert string to permission set for getting permission set of source PermissionSet permissionSetSource; try { SecurityElement securityElement = SecurityElement.FromString(applicationTrustText); permissionSetSource = new System.Security.PermissionSet(PermissionState.None); permissionSetSource.FromXml(securityElement); } catch (XmlSyntaxException) { // This is the condition where we have Malformed XML in the clipboard for application trust // here we will fail silently since we do not want to break arbitrary applications // but since we cannot establish the validity of the application trust content we will fall back to // whatever is more secure return(true); } //extract permission set for the current appdomain which is target PermissionSet permissionSetDestination = SecurityHelper.ExtractAppDomainPermissionSetMinusSiteOfOrigin(); //Compare permissions sets if (!permissionSetDestination.IsSubsetOf(permissionSetSource)) { retVal = true; // in case target is not subset of source revert to unicode or text } } return(retVal); }
public void GetStandardPermissionSetEverythingPermissionSetTest() { PermissionSet everything = PermissionSetFactory.GetStandardPermissionSet(StandardPermissionSet.Everything); // Everything should neither be empty nor full trust Assert.IsFalse(everything.IsUnrestricted()); Assert.IsFalse(everything.IsEmpty()); // Each permission in Everything should be unrestricted, except for SecurityPermission foreach (IPermission permission in everything) { IUnrestrictedPermission unrestricted = permission as IUnrestrictedPermission; SecurityPermission securityPermission = permission as SecurityPermission; if (securityPermission != null) { SecurityPermissionFlag everythingFlags = SecurityPermissionFlag.Assertion | SecurityPermissionFlag.BindingRedirects | SecurityPermissionFlag.ControlAppDomain | SecurityPermissionFlag.ControlDomainPolicy | SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlPrincipal | SecurityPermissionFlag.ControlThread | SecurityPermissionFlag.Execution | SecurityPermissionFlag.Infrastructure | SecurityPermissionFlag.RemotingConfiguration | SecurityPermissionFlag.SerializationFormatter | SecurityPermissionFlag.UnmanagedCode; Assert.AreEqual(everythingFlags, securityPermission.Flags); } else if (unrestricted != null) { Assert.IsTrue(unrestricted.IsUnrestricted()); } } // Everything should be a superset of Internet and LocalIntranet PermissionSet internet = PermissionSetFactory.GetStandardPermissionSet(StandardPermissionSet.Internet); Assert.IsTrue(internet.IsSubsetOf(everything)); Assert.IsFalse(everything.IsSubsetOf(internet)); PermissionSet localIntranet = PermissionSetFactory.GetStandardPermissionSet(StandardPermissionSet.LocalIntranet); Assert.IsTrue(localIntranet.IsSubsetOf(everything)); Assert.IsFalse(everything.IsSubsetOf(localIntranet)); }
protected bool HaveWritePermToDir(string dirPath) { PermissionSet permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission( new FileIOPermission(FileIOPermissionAccess.Write, dirPath)); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return(true); } else { return(false); } }
public static bool HasWriteable(this DirectoryInfo p_dirInfo) { var dirInfo = p_dirInfo; if (dirInfo == null) { return(false); } PermissionSet permissionSet = new PermissionSet(PermissionState.None); var ps = new FileIOPermission(FileIOPermissionAccess.Write, dirInfo.FullName); permissionSet.AddPermission(ps); return(permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)); }
private bool IsEditable(string filePath) { if (!new FileInfo(filePath).IsReadOnly) { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission( FileIOPermissionAccess.Write, filePath); permissionSet.AddPermission(writePermission); return(permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)); } else { return(false); } }
static HostingEnvironment() { try { var permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted)); IsSharedHost = !permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet); } catch (Exception) { IsSharedHost = true; } RootPath = System.Web.Hosting.HostingEnvironment.MapPath("/"); IsHosted = System.Web.Hosting.HostingEnvironment.IsHosted; }
public bool CheckFolderPermissions(string folderPath) { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, folderPath); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return(true); } else { return(false); } }
/// <summary> /// Check if directory is writable. /// </summary> /// <param name="directory">Directory string or full file path</param> /// <returns>true if directory is writeable</returns> public virtual bool CheckWritability(string directory) { directory = Path.GetFullPath(directory); var permissionSet = new PermissionSet(PermissionState.None); var fileIOPermission = new FileIOPermission(FileIOPermissionAccess.Write, directory); permissionSet.AddPermission(fileIOPermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return(true); } return(false); }
public static bool IsGranted(this IPermission permission) { #if DOTNET35 || MONO26 return(SecurityManager.IsGranted(permission)); #else var permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(permission); try { return(permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)); } catch (Exception) { return(false); } #endif }
/// <summary> /// Union a child policy statement into this policy statement /// </summary> internal void InplaceUnion(PolicyStatement childPolicy) { BCLDebug.Assert(childPolicy != null, "childPolicy != null"); if (((Attributes & childPolicy.Attributes) & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive) { throw new PolicyException(Environment.GetResourceString("Policy_MultipleExclusive")); } #if FEATURE_CAS_POLICY // If our code group generated a grant set based upon unverified evidence, or it generated a grant // set strictly less than that of a child group based upon unverified evidence, we need to keep // track of any unverified evidence our child group has. if (childPolicy.HasDependentEvidence) { bool childEvidenceNeedsVerification = m_permSet.IsSubsetOf(childPolicy.GetPermissionSetNoCopy()) && !childPolicy.GetPermissionSetNoCopy().IsSubsetOf(m_permSet); if (HasDependentEvidence || childEvidenceNeedsVerification) { if (m_dependentEvidence == null) { m_dependentEvidence = new List <IDelayEvaluatedEvidence>(); } m_dependentEvidence.AddRange(childPolicy.DependentEvidence); } } #endif // We need to merge together our grant set and attributes. The result of this merge is // dependent upon if we're merging a child marked exclusive or not. If the child is not // exclusive, we need to union in its grant set and or in its attributes. However, if the child // is exclusive then it is the only code group which should have an effect on the resulting // grant set and therefore our grant should be ignored. if ((childPolicy.Attributes & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive) { m_permSet = childPolicy.GetPermissionSetNoCopy(); Attributes = childPolicy.Attributes; } else { m_permSet.InplaceUnion(childPolicy.GetPermissionSetNoCopy()); Attributes = Attributes | childPolicy.Attributes; } }
public Log(string logFile) { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, Environment.CurrentDirectory + "\\" + logFile); permissionSet.AddPermission(writePermission); if (!permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { Console.WriteLine($"No write permission for {logFile}."); MessageBox.Show($"No write permission for {logFile}."); return; } fs = new FileStream(logFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); sw = new StreamWriter(fs); }
public void GetStandardSandboxTest() { Url fileUrl = new Url(@"\\server\share\app"); Url webUrl = new Url("http://www.microsoft.com"); PermissionSet nothing = PermissionSetFactory.GetStandardPermissionSet(StandardPermissionSet.Nothing); PermissionSet internet = PermissionSetFactory.GetStandardPermissionSet(StandardPermissionSet.Internet, webUrl); PermissionSet localIntranet = PermissionSetFactory.GetStandardPermissionSet(StandardPermissionSet.LocalIntranet, fileUrl); // No zone -> nothing Evidence noZone = new Evidence(); PermissionSet noZoneSandbox = PermissionSetFactory.GetStandardSandbox(noZone); Assert.IsTrue(nothing.IsSubsetOf(noZoneSandbox) && noZoneSandbox.IsSubsetOf(nothing)); // Untrusted -> Nothing Evidence untrustedZone = new Evidence(new object[] { new Zone(SecurityZone.Untrusted), webUrl }, null); PermissionSet untrustedSandbox = PermissionSetFactory.GetStandardSandbox(untrustedZone); Assert.IsTrue(nothing.IsSubsetOf(untrustedSandbox) && untrustedSandbox.IsSubsetOf(nothing)); // Internet -> Internet Evidence internetZone = new Evidence(new object[] { new Zone(SecurityZone.Internet), webUrl }, null); PermissionSet internetSandbox = PermissionSetFactory.GetStandardSandbox(internetZone); Assert.IsTrue(internet.IsSubsetOf(internetSandbox) && internetSandbox.IsSubsetOf(internet)); // Trusted -> Internet Evidence trustedZone = new Evidence(new object[] { new Zone(SecurityZone.Trusted), webUrl }, null); PermissionSet trustedSandbox = PermissionSetFactory.GetStandardSandbox(trustedZone); Assert.IsTrue(internet.IsSubsetOf(trustedSandbox) && trustedSandbox.IsSubsetOf(internet)); // Intranet -> LocalIntranet Evidence intranetZone = new Evidence(new object[] { new Zone(SecurityZone.Intranet), fileUrl }, null); PermissionSet intranetSandbox = PermissionSetFactory.GetStandardSandbox(intranetZone); Assert.IsTrue(localIntranet.IsSubsetOf(intranetSandbox) && intranetSandbox.IsSubsetOf(localIntranet)); // MyComputer -> FullTrust Evidence myComputerZone = new Evidence(new object[] { new Zone(SecurityZone.MyComputer), fileUrl }, null); PermissionSet myComputerSandbox = PermissionSetFactory.GetStandardSandbox(myComputerZone); Assert.IsTrue(myComputerSandbox.IsUnrestricted()); }
private static bool isWritable(string filename) { #if NETFULL var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return(true); } else { return(false); } #else return(false); #endif }
private bool FolderPermission(string path) { bool bPermission = false; PermissionSet permissionSet = new PermissionSet(PermissionState.None); FileIOPermission AllPermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, path); permissionSet.AddPermission(AllPermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { bPermission = true; } else { bPermission = false; } return(bPermission); }
private static bool ValidateFilePermissions(string filePath) { string directoryName = Directory.GetParent(filePath).FullName; PermissionSet permissionSet = new PermissionSet(PermissionState.None); FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, directoryName); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return(true); } else { return(false); } }
public static bool IsTracingAvailable() { bool tracingAvailable = false; try { var permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); #if NETSTANDARD2_0 tracingAvailable = false; #else tracingAvailable = permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet); #endif } catch (SecurityException) { } return(tracingAvailable); }
public void ExportToFile(string filename) { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { //using (FileStream fstream = new FileStream(filename, FileMode.Create)) //using (TextWriter writer = new StreamWriter(fstream)) //{ // // try catch block for write permissions // writer.WriteLine("sometext"); //} } else { //perform some recovery action here } }
internal static bool CallerHasPermissionWithAppDomainOptimization(params IPermission[] permissionsToCheck) { if (permissionsToCheck == null) { return(true); } PermissionSet permissionSet = new PermissionSet(PermissionState.None); for (int i = 0; i < permissionsToCheck.Length; i++) { permissionSet.AddPermission(permissionsToCheck[i]); } PermissionSet permissionSet2 = AppDomain.CurrentDomain.PermissionSet; if (permissionSet.IsSubsetOf(permissionSet2)) { return(true); } return(false); }
private static bool AppRequestsBeyondDefaultTrust(ApplicationSecurityInfo info) { try { PermissionSet standardSandbox = SecurityManager.GetStandardSandbox(info.ApplicationEvidence); PermissionSet requestedPermissionSet = GetRequestedPermissionSet(info); if ((standardSandbox == null) && (requestedPermissionSet != null)) { return(true); } if ((standardSandbox != null) && (requestedPermissionSet == null)) { return(false); } return(!requestedPermissionSet.IsSubsetOf(standardSandbox)); } catch (Exception) { return(true); } }
private bool hasWriteAccessToFolder(string folderPath) { try { var permission = new FileIOPermission(FileIOPermissionAccess.Write, folderPath); var permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(permission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return(true); } else { return(false); } } catch (UnauthorizedAccessException) { return(false); } }
public static void PermissionSetCallMethods() { PermissionSet ps = new PermissionSet(new PermissionState()); ps.Assert(); bool containspermissions = ps.ContainsNonCodeAccessPermissions(); PermissionSet ps2 = ps.Copy(); ps.CopyTo(new int[1], 0); ps.Demand(); ps.Equals(ps2); System.Collections.IEnumerator ie = ps.GetEnumerator(); int hash = ps.GetHashCode(); PermissionSet ps3 = ps.Intersect(ps2); bool isempty = ps.IsEmpty(); bool issubsetof = ps.IsSubsetOf(ps2); bool isunrestricted = ps.IsUnrestricted(); string s = ps.ToString(); PermissionSet ps4 = ps.Union(ps2); SecurityElement se = new SecurityElement(""); ps.FromXml(se); se = ps.ToXml(); }
private bool hasWriteAccessToFolder(string folderPath) { try { var permission = new FileIOPermission(FileIOPermissionAccess.Write, folderPath); var permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(permission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return true; } else { return false; } } catch (UnauthorizedAccessException) { return false; } }