SecurityException(string message, AssemblyName assemblyName, #if NOT_PFX PermissionSet grant, PermissionSet refused, #endif MethodInfo method, SecurityAction action, object demanded #if NOT_PFX , IPermission permThatFailed, Evidence evidence #endif ) : base(message) { base.HResult = unchecked ((int)0x8013150A); _assembly = assemblyName; #if NOT_PFX _granted = (grant == null) ? String.Empty : grant.ToString(); _refused = (refused == null) ? String.Empty : refused.ToString(); #endif _method = method; _action = action; _demanded = demanded; #if NOT_PFX _firstperm = permThatFailed; if (_firstperm != null) { permissionType = _firstperm.GetType(); } _evidence = evidence; #endif }
internal SecurityException(string message, PermissionSet granted, PermissionSet refused) : base(message) { base.HResult = unchecked ((int)0x8013150A); _granted = granted.ToString(); _refused = refused.ToString(); }
public void PermissionStateUnrestricted () { PermissionSet ps = new PermissionSet (PermissionState.Unrestricted); Assert ("PermissionStateUnrestricted.IsUnrestricted", ps.IsUnrestricted ()); Assert ("PermissionStateUnrestricted.IsEmpty", !ps.IsEmpty ()); Assert ("PermissionStateUnrestricted.IsReadOnly", !ps.IsReadOnly); AssertEquals ("PermissionStateUnrestricted.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ()); }
public void PermissionStateUnrestricted () { PermissionSet ps = new PermissionSet (PermissionState.Unrestricted); Assert.IsTrue (ps.IsUnrestricted (), "PermissionStateUnrestricted.IsUnrestricted"); Assert.IsTrue (!ps.IsEmpty (), "PermissionStateUnrestricted.IsEmpty"); Assert.IsTrue (!ps.IsReadOnly, "PermissionStateUnrestricted.IsReadOnly"); Assert.AreEqual (ps.ToXml ().ToString (), ps.ToString (), "PermissionStateUnrestricted.ToXml().ToString()==ToString()"); Assert.IsTrue (!ps.ContainsNonCodeAccessPermissions (), "ContainsNonCodeAccessPermissions"); }
public void PermissionSetNull () { // no exception is thrown PermissionSet ps = new PermissionSet (null); Assert.IsTrue (!ps.IsUnrestricted (), "PermissionStateNull.IsUnrestricted"); Assert.IsTrue (ps.IsEmpty (), "PermissionStateNull.IsEmpty"); Assert.IsTrue (!ps.IsReadOnly, "PermissionStateNull.IsReadOnly"); Assert.AreEqual (ps.ToXml ().ToString (), ps.ToString (), "PermissionStateNull.ToXml().ToString()==ToString()"); Assert.IsTrue (!ps.ContainsNonCodeAccessPermissions (), "ContainsNonCodeAccessPermissions"); }
public void PermissionSetNull () { // no exception is thrown PermissionSet ps = new PermissionSet (null); #if NET_2_0 Assert ("PermissionStateNull.IsUnrestricted", !ps.IsUnrestricted ()); Assert ("PermissionStateNull.IsEmpty", ps.IsEmpty ()); #else Assert ("PermissionStateNull.IsUnrestricted", ps.IsUnrestricted ()); Assert ("PermissionStateNull.IsEmpty", !ps.IsEmpty ()); #endif Assert ("PermissionStateNull.IsReadOnly", !ps.IsReadOnly); AssertEquals ("PermissionStateNull.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ()); }
/// <summary>Initializes a new instance of the <see cref="T:System.Security.SecurityException" /> class for an exception caused by an insufficient grant set. </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="assemblyName">An <see cref="T:System.Reflection.AssemblyName" /> that specifies the name of the assembly that caused the exception.</param> /// <param name="grant">A <see cref="T:System.Security.PermissionSet" /> that represents the permissions granted the assembly.</param> /// <param name="refused">A <see cref="T:System.Security.PermissionSet" /> that represents the refused permission or permission set.</param> /// <param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the method that encountered the exception.</param> /// <param name="action">One of the <see cref="T:System.Security.Permissions.SecurityAction" /> values.</param> /// <param name="demanded">The demanded permission, permission set, or permission set collection.</param> /// <param name="permThatFailed">An <see cref="T:System.Security.IPermission" /> that represents the permission that failed.</param> /// <param name="evidence">The <see cref="T:System.Security.Policy.Evidence" /> for the assembly that caused the exception.</param> public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, object demanded, IPermission permThatFailed, Evidence evidence) : base(message) { base.HResult = -2146233078; this._assembly = assemblyName; this._granted = ((grant != null) ? grant.ToString() : string.Empty); this._refused = ((refused != null) ? refused.ToString() : string.Empty); this._method = method; this._action = action; this._demanded = demanded; this._firstperm = permThatFailed; if (this._firstperm != null) { this.permissionType = this._firstperm.GetType(); } this._evidence = evidence; }
internal SecurityException (string message, PermissionSet granted, PermissionSet refused) : base (message) { base.HResult = unchecked ((int)0x8013150A); _granted = granted.ToString (); _refused = refused.ToString (); }
public void ToXml () { PermissionSetCollection psc = new PermissionSetCollection (); SecurityElement se = psc.ToXml (); Assert.IsNull (se.Children, "Children==null for 0"); PermissionSet unr = new PermissionSet (PermissionState.Unrestricted); psc.Add (unr); se = psc.ToXml (); Assert.AreEqual (1, se.Children.Count, "Children==1"); Assert.AreEqual (unr.ToString (), se.Children[0].ToString (), "XML"); }
public void GetSet () { PermissionSetCollection psc = new PermissionSetCollection (); PermissionSet unr = new PermissionSet (PermissionState.Unrestricted); psc.Add (unr); PermissionSet ps = psc.GetSet (0); Assert.AreEqual (unr.ToString (), ps.ToString (), "Same XML"); Assert.IsTrue (Object.ReferenceEquals (unr, ps), "Same Object Reference"); }
public static void PermissionSetDemo() { Console.WriteLine("Executing Permission Set Demo"); try { // Open a permission set. PermissionSet ps1 = new PermissionSet(PermissionState.None); Console.WriteLine("Adding permission to open a file from a file dialog box."); // Add a permission to the permission set. ps1.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Open)); Console.WriteLine("Demanding Permission to open a file."); ps1.Demand(); Console.WriteLine("Demand succeeded."); Console.WriteLine("Adding permission to save a file from a file dialog box."); ps1.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Save)); Console.WriteLine("Demanding permission to open and save a file."); ps1.Demand(); Console.WriteLine("Demand succeeded."); Console.WriteLine("Adding a permission to read environment variable USERNAME."); ps1.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME")); ps1.Demand(); Console.WriteLine("Demand succeeded."); Console.WriteLine("Adding permission to read environment variable COMPUTERNAME."); ps1.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "COMPUTERNAME")); // Demand all the permissions in the set. Console.WriteLine("Demand all permissions."); ps1.Demand(); Console.WriteLine("Demand succeeded."); // Display the number of permissions in the set. Console.WriteLine("Number of permissions = " + ps1.Count); // Display the value of the IsSynchronized property. Console.WriteLine("IsSynchronized property = " + ps1.IsSynchronized); // Display the value of the IsReadOnly property. Console.WriteLine("IsReadOnly property = " + ps1.IsReadOnly); // Display the value of the SyncRoot property. Console.WriteLine("SyncRoot property = " + ps1.SyncRoot); // Display the result of a call to the ContainsNonCodeAccessPermissions method. // Gets a value indicating whether the PermissionSet contains permissions // that are not derived from CodeAccessPermission. // Returns true if the PermissionSet contains permissions that are not // derived from CodeAccessPermission; otherwise, false. Console.WriteLine("ContainsNonCodeAccessPermissions method returned " + ps1.ContainsNonCodeAccessPermissions()); Console.WriteLine("Value of the permission set ToString = \n" + ps1.ToString()); PermissionSet ps2 = new PermissionSet(PermissionState.None); // Create a second permission set and compare it to the first permission set. ps2.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME")); ps2.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Write, "COMPUTERNAME")); Console.WriteLine("Permission set 2 = " + ps2); IEnumerator list = ps1.GetEnumerator(); Console.WriteLine("Permissions in first permission set:"); foreach (var permission in ps1) Console.WriteLine(permission.ToString()); Console.WriteLine("Second permission IsSubSetOf first permission = " + ps2.IsSubsetOf(ps1)); // Display the intersection of two permission sets. PermissionSet ps3 = ps2.Intersect(ps1); Console.WriteLine("The intersection of the first permission set and the second permission set = " + ps3.ToString()); // Create a new permission set. PermissionSet ps4 = new PermissionSet(PermissionState.None); ps4.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, "C:\\Temp\\Testfile.txt")); ps4.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, "C:\\Temp\\Testfile.txt")); // Display the union of two permission sets. PermissionSet ps5 = ps3.Union(ps4); Console.WriteLine("The union of permission set 3 and permission set 4 = " + ps5.ToString()); // Remove FileIOPermission from the permission set. ps5.RemovePermission(typeof(FileIOPermission)); Console.WriteLine("The last permission set after removing FileIOPermission = " + ps5.ToString()); // Change the permission set using SetPermission ps5.SetPermission(new EnvironmentPermission(EnvironmentPermissionAccess.AllAccess, "USERNAME")); Console.WriteLine("Permission set after SetPermission = " + ps5.ToString()); // Display result of ToXml and FromXml operations. PermissionSet ps6 = new PermissionSet(PermissionState.None); ps6.FromXml(ps5.ToXml()); Console.WriteLine("Result of ToFromXml = " + ps6.ToString() + "\n"); // Display result of PermissionSet.GetEnumerator. IEnumerator psEnumerator = ps1.GetEnumerator(); while (psEnumerator.MoveNext()) { Console.WriteLine(psEnumerator.Current.ToString()); } // Check for an unrestricted permission set. PermissionSet ps7 = new PermissionSet(PermissionState.Unrestricted); Console.WriteLine("Permission set is unrestricted = " + ps7.IsUnrestricted()); // Create and display a copy of a permission set. ps7 = ps5.Copy(); Console.WriteLine("Result of copy = " + ps7.ToString()); } catch (Exception e) { Console.WriteLine(e.Message.ToString()); } }
public void ConvertPermissionSet_BinaryToBinary () { PermissionSet ps = new PermissionSet (PermissionState.None); byte[] data = Encoding.ASCII.GetBytes (ps.ToString ()); byte[] result = PermissionSet.ConvertPermissionSet ("XML", data, "BINARY"); byte[] result2 = PermissionSet.ConvertPermissionSet ("BINARY", result, "BINARY"); // there's only a little difference - but it doesn't throw an exception //Assert.IsTrue (BitConverter.ToString (result) != BitConverter.ToString (result2), "BINARY!=BINARY"); }
public void PermissionSetPermissionSet () { FileDialogPermission fdp = new FileDialogPermission (FileDialogPermissionAccess.Open); PermissionSet ps1 = new PermissionSet (PermissionState.None); ps1.AddPermission (fdp); Assert ("ps1.IsEmpty", !ps1.IsEmpty ()); PermissionSet ps = new PermissionSet (ps1); Assert ("PermissionSetPermissionSet.IsUnrestricted", !ps.IsUnrestricted ()); Assert ("PermissionSetPermissionSet.IsEmpty", !ps.IsEmpty ()); Assert ("PermissionSetPermissionSet.IsReadOnly", !ps.IsReadOnly); AssertEquals ("PermissionSetPermissionSet.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ()); }
public static string[] PermissionSetToIdentityList(PermissionSet permissionSet) { string psXml = permissionSet != null ? permissionSet.ToString() : "<PermissionSet/>"; XmlDocument psDocument = new XmlDocument(); // CA3057: DoNotUseLoadXml. Suppressed since 'psXml' is a trusted or a constant string. psDocument.LoadXml(psXml); return XmlToIdentityList(psDocument.DocumentElement); }
internal SecurityException(string message, PermissionSet granted, PermissionSet refused) : base(message) { base.HResult = -2146233078; this._granted = granted.ToString(); this._refused = refused.ToString(); }
static private PermissionSet ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, out PermissionSet denied, bool checkExecutionPermission) { PermissionSet requested; PermissionSet optional; PermissionSet allowed; Exception savedException = null; // We don't want to recurse back into here as a result of a // stackwalk during resolution. So simply assert full trust (this // implies that custom permissions cannot use any permissions that // don't implement IUnrestrictedPermission. // PermissionSet.s_fullTrust.Assert(); // The requested set is the union of the minimal request and the // optional request. Minimal request defaults to empty, optional // is "AllPossible" (includes any permission that can be defined) // which is symbolized by null. optional = optPset; if (reqdPset == null) { requested = optional; } else { // If optional is null, the requested set becomes null/"AllPossible". requested = optional == null ? null : reqdPset.Union(optional); } // Make sure that the right to execute is requested (if this feature is // enabled). if (requested != null && !requested.IsUnrestricted() && CheckExecution()) { requested.AddPermission(executionSecurityPermission); } if (InitPolicy()) { // If we aren't passed any evidence, just make an empty object // If we are passed evidence, copy it before passing it // to the policy manager. // Note: this is not a deep copy, the pieces of evidence within the // Evidence object can still be altered and affect the originals. if (evidence == null) { evidence = new Evidence(); } else { evidence = evidence.ShallowCopy(); } evidence.AddHost(new PermissionRequestEvidence(reqdPset, optPset, denyPset)); // We need to make sure that no stray exceptions come out of Resolve so // we wrap it in a try block. try { allowed = polmgr.Resolve(evidence, requested); } catch (Exception e) { #if _DEBUG if (debug) { DEBUG_OUT("Exception during resolve"); DEBUG_OUT(e.GetType().FullName); DEBUG_OUT(e.Message); DEBUG_OUT(e.StackTrace); } #endif // If we get a policy exception, we are done are we are going to fail to // load no matter what. if (e is PolicyException) { throw e; } // If we get any other kid of exception, we set the allowed set to the // empty set and continue processing as normal. This allows assemblies // that make no request to be loaded but blocks any assembly that // makes a request from being loaded. This seems like a valid design to // me -- gregfee 6/19/2000 savedException = e; allowed = new PermissionSet(); } } else { denied = null; return(null); } #if _DEBUG if (debug) { DEBUG_OUT("ResolvePolicy:"); IEnumerator enumerator = evidence.GetEnumerator(); DEBUG_OUT("Evidence:"); while (enumerator.MoveNext()) { Object obj = enumerator.Current; if (obj is Site) { DEBUG_OUT(((Site)obj).ToXml().ToString()); } else if (obj is Zone) { DEBUG_OUT(((Zone)obj).ToXml().ToString()); } else if (obj is Url) { DEBUG_OUT(((Url)obj).ToXml().ToString()); } else if (obj is Publisher) { DEBUG_OUT(((Publisher)obj).ToXml().ToString()); } else if (obj is StrongName) { DEBUG_OUT(((StrongName)obj).ToXml().ToString()); } else if (obj is PermissionRequestEvidence) { DEBUG_OUT(((PermissionRequestEvidence)obj).ToXml().ToString()); } } DEBUG_OUT("Required permissions:"); DEBUG_OUT(reqdPset != null ? reqdPset.ToString() : "<null>"); DEBUG_OUT("Optional permissions:"); DEBUG_OUT(optPset != null ? optPset.ToString() : "<null>"); DEBUG_OUT("Denied permissions:"); DEBUG_OUT(denyPset != null ? denyPset.ToString() : "<null>"); DEBUG_OUT("Requested permissions:"); DEBUG_OUT(requested != null ? requested.ToString() : "<null>"); DEBUG_OUT("Granted permissions:"); DEBUG_OUT(allowed != null ? allowed.ToString() : "<null>"); } #endif // Check that we were granted the right to execute. if (!allowed.IsUnrestricted() && checkExecutionPermission && CheckExecution()) { SecurityPermission secPerm = (SecurityPermission)allowed.GetPermission(securityPermissionType); if (secPerm == null || !executionSecurityPermission.IsSubsetOf(secPerm)) { #if _DEBUG DEBUG_OUT("No execute permission"); #endif throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"), System.__HResults.CORSEC_E_NO_EXEC_PERM, savedException); } } // Check that we were granted at least the minimal set we asked for. Do // this before pruning away any overlap with the refused set so that // users have the flexability of defining minimal permissions that are // only expressable as set differences (e.g. allow access to "C:\" but // disallow "C:\Windows"). if (reqdPset != null && !reqdPset.IsSubsetOf(allowed)) { #if _DEBUG DEBUG_OUT("Didn't get required permissions"); #endif throw new PolicyException(Environment.GetResourceString("Policy_NoRequiredPermission"), System.__HResults.CORSEC_E_MIN_GRANT_FAIL, savedException); } // Remove any granted permissions that are safe subsets of some denied // permission. The remaining denied permissions (if any) are returned // along with the modified grant set for use in checks. if (denyPset != null) { denied = denyPset.Copy(); allowed.MergeDeniedSet(denied); if (denied.IsEmpty()) { denied = null; } } else { denied = null; } #if _DEBUG if (debug) { DEBUG_OUT("Final denied permissions:"); DEBUG_OUT(denied != null ? denied.ToString() : "<null>"); } #endif return(allowed); }
/// <include file='doc\PermissionSet.uex' path='docs/doc[@for="PermissionSet.IsSubsetOf"]/*' /> public virtual bool IsSubsetOf(PermissionSet target) { #if _DEBUG if (debug) DEBUG_WRITE("IsSubsetOf\n" + "Other:\n" + (target == null ? "<null>" : target.ToString()) + "\nMe:\n" + ToString()); #endif if (target == null || target.IsEmpty()) return this.IsEmpty(); else if (this.IsUnrestricted() && !target.IsUnrestricted()) { return false; } else if (this.m_normalPermSet != null && !this.m_normalPermSet.IsSubsetOf( target.m_normalPermSet )) { return false; } else if (target.IsUnrestricted() && !this.ContainsNonCodeAccessPermissions()) { return true; } else { return this.m_unrestrictedPermSet == null || this.m_unrestrictedPermSet.IsSubsetOf( target.m_unrestrictedPermSet ); } }
public PermissionSet Resolve(Evidence evidence, PermissionSet request) { #if _DEBUG if (debug) { DEBUG_OUT("PolicyManager::Resolve"); IEnumerator evidenceEnumerator = evidence.GetEnumerator(); DEBUG_OUT("Evidence:"); while (evidenceEnumerator.MoveNext()) { Object obj = evidenceEnumerator.Current; if (obj is Site) { DEBUG_OUT(((Site)obj).ToXml().ToString()); } else if (obj is Zone) { DEBUG_OUT(((Zone)obj).ToXml().ToString()); } else if (obj is Url) { DEBUG_OUT(((Url)obj).ToXml().ToString()); } else if (obj is StrongName) { DEBUG_OUT(((StrongName)obj).ToXml().ToString()); } else if (obj is PermissionRequestEvidence) { DEBUG_OUT(((PermissionRequestEvidence)obj).ToXml().ToString()); } } } #endif // We set grant to null to represent "AllPossible" PermissionSet grant = null; PolicyStatement policy; PolicyLevel currentLevel = null; IEnumerator levelEnumerator = m_levels.GetEnumerator(); char[] serializedEvidence = MakeEvidenceArray(evidence, false); int count = evidence.Count; bool testApplicationLevels = false; while (levelEnumerator.MoveNext()) { currentLevel = (PolicyLevel)levelEnumerator.Current; policy = currentLevel.Resolve(evidence, count, serializedEvidence); // If the grant is "AllPossible", the intersection is just the other permission set. // Otherwise, do an inplace intersection (since we know we can alter the grant set since // it is a copy of the first policy statement's permission set). if (grant == null) { grant = policy.PermissionSet; } else { // An exception somewhere in here means that a permission // failed some operation. This simply means that it will be // dropped from the grant set which is safe operation that // can be ignored. try { grant.InplaceIntersect(policy.GetPermissionSetNoCopy()); } catch (Exception) { } } #if _DEBUG if (debug) { DEBUG_OUT("Level = " + currentLevel.Label); DEBUG_OUT("policy =\n" + policy.ToXml().ToString()); DEBUG_OUT("grant so far =\n" + grant.ToXml().ToString()); } #endif if (grant.IsEmpty()) { break; } else if ((policy.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal) { if (!currentLevel.Label.Equals("AppDomain")) { testApplicationLevels = true; } break; } } if (testApplicationLevels) { PolicyLevel appDomainLevel = null; for (int i = m_levels.Count - 1; i >= 0; --i) { currentLevel = (PolicyLevel)m_levels[i]; if (currentLevel.Label.Equals("AppDomain")) { appDomainLevel = currentLevel; break; } } if (appDomainLevel != null) { policy = appDomainLevel.Resolve(evidence, count, serializedEvidence); grant.InplaceIntersect(policy.GetPermissionSetNoCopy()); } } #if _DEBUG if (debug) { DEBUG_OUT("granted =\n" + grant.ToString()); DEBUG_OUT("request =\n" + (request != null ? request.ToString() : "<null>")); DEBUG_OUT("awarded =\n" + (request != null ? grant.Intersect(request).ToString() : grant.ToString())); } #endif try { if (request != null) { grant.InplaceIntersect(request); } } catch (Exception) { } #if _DEBUG if (debug) { DEBUG_OUT("granted after intersect w/ request =\n" + grant.ToString()); } #endif // Each piece of evidence can possibly create an identity permission that we // need to add to our grant set. Therefore, for all pieces of evidence that // implement the IIdentityPermissionFactory interface, ask it for its // adjoining identity permission and add it to the grant. IEnumerator enumerator = evidence.GetHostEnumerator(); while (enumerator.MoveNext()) { try { Object obj = enumerator.Current; IIdentityPermissionFactory factory = obj as IIdentityPermissionFactory; if (factory != null) { IPermission perm = factory.CreateIdentityPermission(evidence); if (perm != null) { grant.AddPermission(perm); } } } catch (Exception) { } } #if _DEBUG if (debug) { DEBUG_OUT("awarded with identity =\n" + grant.ToString()); } #endif return(grant); }
internal static XmlDocument PermissionSetToXml(PermissionSet ps) { XmlDocument document = new XmlDocument(); string xml = (ps != null) ? ps.ToString() : "<PermissionSet/>"; document.LoadXml(xml); XmlDocument document2 = new XmlDocument(); XmlElement newChild = XmlUtil.CloneElementToDocument(document.DocumentElement, document2, "urn:schemas-microsoft-com:asm.v2"); document2.AppendChild(newChild); return document2; }
public static string[] PermissionSetToIdentityList(PermissionSet permissionSet) { string xml = (permissionSet != null) ? permissionSet.ToString() : "<PermissionSet/>"; XmlDocument document = new XmlDocument(); document.LoadXml(xml); return XmlToIdentityList(document.DocumentElement); }
public SecurityException (string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, object demanded, IPermission permThatFailed, Evidence evidence) : base (message) { base.HResult = unchecked ((int)0x8013150A); _assembly = assemblyName; _granted = (grant == null) ? String.Empty : grant.ToString (); _refused = (refused == null) ? String.Empty : refused.ToString (); _method = method; _action = action; _demanded = demanded; _firstperm = permThatFailed; if (_firstperm != null) permissionType = _firstperm.GetType (); _evidence = evidence; }
internal bool IsSubsetOfHelper(PermissionSet target, IsSubsetOfType type, out IPermission firstPermThatFailed, bool ignoreNonCas) { #if _DEBUG if (debug) DEBUG_WRITE("IsSubsetOf\n" + "Other:\n" + (target == null ? "<null>" : target.ToString()) + "\nMe:\n" + ToString()); #endif firstPermThatFailed = null; if (target == null || target.FastIsEmpty()) { if(this.IsEmpty()) return true; else { firstPermThatFailed = GetFirstPerm(); return false; } } else if (this.IsUnrestricted() && !target.IsUnrestricted()) return false; else if (this.m_permSet == null) return true; else { target.CheckSet(); for (int i = m_permSet.GetStartingIndex(); i <= this.m_permSet.GetMaxUsedIndex(); ++i) { IPermission thisPerm = this.GetPermission(i); if (thisPerm == null || thisPerm.IsSubsetOf(null)) continue; IPermission targetPerm = target.GetPermission(i); #if _DEBUG PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); Contract.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized"); #endif if (target.m_Unrestricted) continue; // targetPerm can be null here, but that is fine since it thisPerm is a subset // of empty/null then we can continue in the loop. CodeAccessPermission cap = thisPerm as CodeAccessPermission; if(cap == null) { if (!ignoreNonCas && !thisPerm.IsSubsetOf( targetPerm )) { firstPermThatFailed = thisPerm; return false; } } else { firstPermThatFailed = thisPerm; switch(type) { case IsSubsetOfType.Normal: if (!thisPerm.IsSubsetOf( targetPerm )) return false; break; case IsSubsetOfType.CheckDemand: if (!cap.CheckDemand( (CodeAccessPermission)targetPerm )) return false; break; case IsSubsetOfType.CheckPermitOnly: if (!cap.CheckPermitOnly( (CodeAccessPermission)targetPerm )) return false; break; case IsSubsetOfType.CheckAssertion: if (!cap.CheckAssert( (CodeAccessPermission)targetPerm )) return false; break; } firstPermThatFailed = null; } } } return true; }
public void ConvertPermissionSet_XmlToXml () { PermissionSet ps = new PermissionSet (PermissionState.None); byte[] data = Encoding.ASCII.GetBytes (ps.ToString ()); byte[] result = PermissionSet.ConvertPermissionSet ("XML", data, "XML"); Assert.AreEqual (Encoding.ASCII.GetString (result), ps.ToString (), "PS-XML"); result = PermissionSet.ConvertPermissionSet ("XMLASCII", data, "XMLASCII"); Assert.AreEqual (Encoding.ASCII.GetString (result), ps.ToString (), "PS-XMLASCII"); }
internal static XmlDocument PermissionSetToXml(PermissionSet ps) { XmlDocument inputDocument = new XmlDocument(); string xml = (ps != null) ? ps.ToString() : "<PermissionSet/>"; // CA3057: DoNotUseLoadXml. Suppressed since 'xml' is a trusted or a constant string. inputDocument.LoadXml(xml); XmlDocument outputDocument = new XmlDocument(); XmlElement psElement = XmlUtil.CloneElementToDocument(inputDocument.DocumentElement, outputDocument, XmlNamespaces.asmv2); outputDocument.AppendChild(psElement); return outputDocument; }
public void ToXmlUnrestricted () { PermissionSet ps = new PermissionSet (PermissionState.Unrestricted); SecurityElement se = ps.ToXml (); Assert ("Unrestricted.ToString().StartsWith", ps.ToString().StartsWith ("<PermissionSet")); AssertEquals ("Unrestricted.class", "System.Security.PermissionSet", (se.Attributes ["class"] as string)); AssertEquals ("Unrestricted.version", "1", (se.Attributes ["version"] as string)); AssertEquals ("Unrestricted.Unrestricted", "true", (se.Attributes ["Unrestricted"] as string)); }
public void ToXmlUnrestricted () { PermissionSet ps = new PermissionSet (PermissionState.Unrestricted); SecurityElement se = ps.ToXml (); Assert.IsTrue (ps.ToString().StartsWith ("<PermissionSet"), "Unrestricted.ToString().StartsWith"); Assert.AreEqual ("System.Security.PermissionSet", (se.Attributes ["class"] as string), "Unrestricted.class"); Assert.AreEqual ("1", (se.Attributes ["version"] as string), "Unrestricted.version"); Assert.AreEqual ("true", (se.Attributes ["Unrestricted"] as string), "Unrestricted.Unrestricted"); }
public void Copy_References () { PermissionSet none = new PermissionSet (PermissionState.None); PermissionSetCollection psc = new PermissionSetCollection (); psc.Add (none); PermissionSetCollection copy = psc.Copy (); Assert.AreEqual (1, copy.PermissionSets.Count, "Count-1"); string before = psc.ToString (); none.AddPermission (new SecurityPermission (SecurityPermissionFlag.Assertion)); Assert.AreEqual (none.ToString (), psc.PermissionSets[0].ToString (), "psc"); Assert.AreEqual (before, copy.ToString (), "copy"); }
public void ConvertPermissionSet_XmlToBinary () { PermissionSet ps = new PermissionSet (PermissionState.None); byte[] data = Encoding.ASCII.GetBytes (ps.ToString ()); byte[] result = PermissionSet.ConvertPermissionSet ("XML", data, "BINARY"); byte[] result2 = PermissionSet.ConvertPermissionSet ("XMLASCII", data, "BINARY"); Assert.AreEqual (BitConverter.ToString (result), BitConverter.ToString (result2), "XML==XMLASCII"); byte[] back = PermissionSet.ConvertPermissionSet ("BINARY", result, "XML"); Assert.AreEqual (Encoding.ASCII.GetString (back), ps.ToString (), "PS-XML"); back = PermissionSet.ConvertPermissionSet ("BINARY", result2, "XMLASCII"); Assert.AreEqual (Encoding.ASCII.GetString (back), ps.ToString (), "PS-XMLASCII"); }
/// <include file='doc\SecurityManager.uex' path='docs/doc[@for="SecurityManager.ResolvePolicy"]/*' /> static public PermissionSet ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, out PermissionSet denied) { PermissionSet requested; PermissionSet optional; PermissionSet allowed; Exception savedException = null; // We don't want to recurse back into here as a result of a // stackwalk during resolution. So simply assert full trust (this // implies that custom permissions cannot use any permissions that // don't implement IUnrestrictedPermission. // PermissionSet.s_fullTrust.Assert(); // The requested set is the union of the minimal request and the // optional request. Minimal request defaults to empty, optional // is "AllPossible" (includes any permission that can be defined) // which is symbolized by null. optional = optPset; if (reqdPset == null) { requested = optional; } else { // If optional is null, the requested set becomes null/"AllPossible". requested = optional == null ? null : reqdPset.Union(optional); } // Make sure that the right to execute is requested (if this feature is // enabled). if (requested != null && !requested.IsUnrestricted() && CheckExecution()) { requested.AddPermission( executionSecurityPermission ); } if (InitPolicy()) { // If we aren't passed any evidence, just make an empty object // If we are passed evidence, copy it before passing it // to the policy manager. // Note: this is not a deep copy, the pieces of evidence within the // Evidence object can still be altered and affect the originals. if (evidence == null) evidence = new Evidence(); else evidence = evidence.ShallowCopy(); evidence.AddHost(new PermissionRequestEvidence(reqdPset, optPset, denyPset)); // We need to make sure that no stray exceptions come out of Resolve so // we wrap it in a try block. try { allowed = polmgr.Resolve(evidence,requested); } catch (Exception e) { #if _DEBUG if (debug) { DEBUG_OUT( "Exception during resolve" ); DEBUG_OUT( e.GetType().FullName ); DEBUG_OUT( e.Message ); DEBUG_OUT( e.StackTrace ); } #endif // If we get a policy exception, we are done are we are going to fail to // load no matter what. if (e is PolicyException) throw e; // If we get any other kid of exception, we set the allowed set to the // empty set and continue processing as normal. This allows assemblies // that make no request to be loaded but blocks any assembly that // makes a request from being loaded. savedException = e; allowed = new PermissionSet(); } } else { denied = null; return null; } #if _DEBUG if (debug) { DEBUG_OUT("ResolvePolicy:"); IEnumerator enumerator = evidence.GetEnumerator(); DEBUG_OUT("Evidence:"); while (enumerator.MoveNext()) { Object obj = enumerator.Current; if (obj is Site) { DEBUG_OUT( ((Site)obj).ToXml().ToString() ); } else if (obj is Zone) { DEBUG_OUT( ((Zone)obj).ToXml().ToString() ); } else if (obj is Url) { DEBUG_OUT( ((Url)obj).ToXml().ToString() ); } else if (obj is StrongName) { DEBUG_OUT( ((StrongName)obj).ToXml().ToString() ); } else if (obj is PermissionRequestEvidence) { DEBUG_OUT( ((PermissionRequestEvidence)obj).ToXml().ToString() ); } } DEBUG_OUT("Required permissions:"); DEBUG_OUT(reqdPset != null ? reqdPset.ToString() : "<null>"); DEBUG_OUT("Optional permissions:"); DEBUG_OUT(optPset != null ? optPset.ToString() : "<null>"); DEBUG_OUT("Denied permissions:"); DEBUG_OUT(denyPset != null ? denyPset.ToString() : "<null>"); DEBUG_OUT("Requested permissions:"); DEBUG_OUT(requested != null ? requested.ToString() : "<null>"); DEBUG_OUT("Granted permissions:"); DEBUG_OUT(allowed != null ? allowed.ToString() : "<null>"); } #endif // Check that we were granted the right to execute. if (!allowed.IsUnrestricted() && CheckExecution()) { SecurityPermission secPerm = (SecurityPermission)allowed.GetPermission( securityPermissionType ); if (secPerm == null || !executionSecurityPermission.IsSubsetOf( secPerm )) { #if _DEBUG DEBUG_OUT( "No execute permission" ); #endif throw new PolicyException(Environment.GetResourceString( "Policy_NoExecutionPermission" ), System.__HResults.CORSEC_E_NO_EXEC_PERM, savedException ); } } // Check that we were granted at least the minimal set we asked for. Do // this before pruning away any overlap with the refused set so that // users have the flexability of defining minimal permissions that are // only expressable as set differences (e.g. allow access to "C:\" but // disallow "C:\Windows"). if (reqdPset != null && !reqdPset.IsSubsetOf(allowed)) { #if _DEBUG DEBUG_OUT( "Didn't get required permissions" ); #endif throw new PolicyException(Environment.GetResourceString( "Policy_NoRequiredPermission" ), System.__HResults.CORSEC_E_MIN_GRANT_FAIL, savedException ); } // Remove any granted permissions that are safe subsets of some denied // permission. The remaining denied permissions (if any) are returned // along with the modified grant set for use in checks. if (denyPset != null) { denied = denyPset.Copy(); allowed.MergeDeniedSet(denied); if (denied.IsEmpty()) denied = null; } else denied = null; #if _DEBUG if (debug) { DEBUG_OUT("Final denied permissions:"); DEBUG_OUT(denied != null ? denied.ToString() : "<null>"); } #endif return allowed; }
public void ConvertPermissionSet_XmlAsciiToXmlUnicode () { PermissionSet ps = new PermissionSet (PermissionState.Unrestricted); byte[] data = Encoding.Unicode.GetBytes (ps.ToString ()); byte[] result = PermissionSet.ConvertPermissionSet ("XMLASCII", data, "XMLUNICODE"); // the method isn't intended to convert between ASCII and Unicode }
public PermissionSet Resolve(Evidence evidence, PermissionSet request) { #if _DEBUG if (debug) { DEBUG_OUT("PolicyManager::Resolve"); IEnumerator evidenceEnumerator = evidence.GetEnumerator(); DEBUG_OUT("Evidence:"); while (evidenceEnumerator.MoveNext()) { Object obj = evidenceEnumerator.Current; if (obj is Site) { DEBUG_OUT( ((Site)obj).ToXml().ToString() ); } else if (obj is Zone) { DEBUG_OUT( ((Zone)obj).ToXml().ToString() ); } else if (obj is Url) { DEBUG_OUT( ((Url)obj).ToXml().ToString() ); } else if (obj is StrongName) { DEBUG_OUT( ((StrongName)obj).ToXml().ToString() ); } else if (obj is PermissionRequestEvidence) { DEBUG_OUT( ((PermissionRequestEvidence)obj).ToXml().ToString() ); } } } #endif // We set grant to null to represent "AllPossible" PermissionSet grant = null; PolicyStatement policy; PolicyLevel currentLevel = null; IEnumerator levelEnumerator = m_levels.GetEnumerator(); char[] serializedEvidence = MakeEvidenceArray( evidence, false ); int count = evidence.Count; bool testApplicationLevels = false; while (levelEnumerator.MoveNext()) { currentLevel = (PolicyLevel)levelEnumerator.Current; policy = currentLevel.Resolve( evidence, count, serializedEvidence ); // If the grant is "AllPossible", the intersection is just the other permission set. // Otherwise, do an inplace intersection (since we know we can alter the grant set since // it is a copy of the first policy statement's permission set). if (grant == null) { grant = policy.PermissionSet; } else { // An exception somewhere in here means that a permission // failed some operation. This simply means that it will be // dropped from the grant set which is safe operation that // can be ignored. try { grant.InplaceIntersect( policy.GetPermissionSetNoCopy() ); } catch (Exception) { } } #if _DEBUG if (debug) { DEBUG_OUT( "Level = " + currentLevel.Label ); DEBUG_OUT( "policy =\n" + policy.ToXml().ToString() ); DEBUG_OUT( "grant so far =\n" + grant.ToXml().ToString() ); } #endif if (grant.IsEmpty()) { break; } else if ((policy.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal) { if (!currentLevel.Label.Equals( "AppDomain" )) { testApplicationLevels = true; } break; } } if (testApplicationLevels) { PolicyLevel appDomainLevel = null; for (int i = m_levels.Count - 1; i >= 0; --i) { currentLevel = (PolicyLevel)m_levels[i]; if (currentLevel.Label.Equals( "AppDomain" )) { appDomainLevel = currentLevel; break; } } if (appDomainLevel != null) { policy = appDomainLevel.Resolve( evidence, count, serializedEvidence ); grant.InplaceIntersect( policy.GetPermissionSetNoCopy() ); } } #if _DEBUG if (debug) { DEBUG_OUT( "granted =\n" + grant.ToString() ); DEBUG_OUT( "request =\n" + (request != null ? request.ToString() : "<null>") ); DEBUG_OUT( "awarded =\n" + (request != null ? grant.Intersect( request ).ToString() : grant.ToString()) ); } #endif try { if(request != null) grant.InplaceIntersect( request ); } catch (Exception) { } #if _DEBUG if (debug) { DEBUG_OUT("granted after intersect w/ request =\n" + grant.ToString()); } #endif // Each piece of evidence can possibly create an identity permission that we // need to add to our grant set. Therefore, for all pieces of evidence that // implement the IIdentityPermissionFactory interface, ask it for its // adjoining identity permission and add it to the grant. IEnumerator enumerator = evidence.GetHostEnumerator(); while (enumerator.MoveNext()) { try { Object obj = enumerator.Current; IIdentityPermissionFactory factory = obj as IIdentityPermissionFactory; if (factory != null) { IPermission perm = factory.CreateIdentityPermission( evidence ); if (perm != null) { grant.AddPermission( perm ); } } } catch (Exception) { } } #if _DEBUG if (debug) { DEBUG_OUT( "awarded with identity =\n" + grant.ToString() ); } #endif return grant; }
public void PermissionSetPermissionSet () { FileDialogPermission fdp = new FileDialogPermission (FileDialogPermissionAccess.Open); PermissionSet ps1 = new PermissionSet (PermissionState.None); ps1.AddPermission (fdp); Assert.IsTrue (!ps1.IsEmpty (), "ps1.IsEmpty"); PermissionSet ps = new PermissionSet (ps1); Assert.IsTrue (!ps.IsUnrestricted (), "PermissionSetPermissionSet.IsUnrestricted"); Assert.IsTrue (!ps.IsEmpty (), "PermissionSetPermissionSet.IsEmpty"); Assert.IsTrue (!ps.IsReadOnly, "PermissionSetPermissionSet.IsReadOnly"); Assert.AreEqual (ps.ToXml ().ToString (), ps.ToString (), "PermissionSetPermissionSet.ToXml().ToString()==ToString()"); Assert.IsTrue (!ps.ContainsNonCodeAccessPermissions (), "ContainsNonCodeAccessPermissions"); }
// FIXME little documentation in Fx 2.0 beta 1 public static byte[] ConvertPermissionSet(string inFormat, byte[] inData, string outFormat) { if (inFormat == null) { throw new ArgumentNullException("inFormat"); } if (outFormat == null) { throw new ArgumentNullException("outFormat"); } if (inData == null) { return(null); } if (inFormat == outFormat) { return(inData); } PermissionSet ps = null; if (inFormat == "BINARY") { if (outFormat.StartsWith("XML")) { using (MemoryStream ms = new MemoryStream(inData)) { BinaryFormatter formatter = new BinaryFormatter(); ps = (PermissionSet)formatter.Deserialize(ms); ms.Close(); } string xml = ps.ToString(); switch (outFormat) { case "XML": case "XMLASCII": return(Encoding.ASCII.GetBytes(xml)); case "XMLUNICODE": return(Encoding.Unicode.GetBytes(xml)); } } } else if (inFormat.StartsWith("XML")) { if (outFormat == "BINARY") { string xml = null; switch (inFormat) { case "XML": case "XMLASCII": xml = Encoding.ASCII.GetString(inData); break; case "XMLUNICODE": xml = Encoding.Unicode.GetString(inData); break; } if (xml != null) { ps = new PermissionSet(PermissionState.None); ps.FromXml(SecurityElement.FromString(xml)); MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, ps); ms.Close(); return(ms.ToArray()); } } else if (outFormat.StartsWith("XML")) { string msg = String.Format(Locale.GetText("Can't convert from {0} to {1}"), inFormat, outFormat); #if NET_2_0 throw new XmlSyntaxException(msg); #else throw new ArgumentException(msg); #endif } } else { // unknown inFormat, returns null return(null); } // unknown outFormat, throw throw new SerializationException(String.Format(Locale.GetText("Unknown output format {0}."), outFormat)); }