The Labs \ Source Viewer \ SSCLI \ System.Security \ SecurityException

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. /*=============================================================================
  16. **
  17. ** Class: SecurityException
  18. **
  19. **
  20. ** Purpose: Exception class for security
  21. **
  22. **
  23. =============================================================================*/
  24. namespace System.Security
  25. {
  26.     using System.Security;
  27.     using System;
  28.     using System.Runtime.Serialization;
  29.     using System.Security.Permissions;
  30.     using System.Reflection;
  31.     using System.Text;
  32.     using System.Security.Policy;
  33.     using System.IO;
  34.     using System.Runtime.Serialization.Formatters.Binary;
  35.     using System.Globalization;
  36.     using System.Security.Util;
  37.    
  38.     [System.Runtime.InteropServices.ComVisible(true)]
  39.     [Serializable()]
  40.     public class SecurityException : SystemException
  41.     {
  42.         private string m_debugString;
  43.         // NOTE: If you change the name of this field, you'll have to update SOS as well!
  44.         private SecurityAction m_action;
  45.         [NonSerialized()]
  46.         private Type m_typeOfPermissionThatFailed;
  47.         private string m_permissionThatFailed;
  48.         private string m_demanded;
  49.         private string m_granted;
  50.         private string m_refused;
  51.         private string m_denied;
  52.         private string m_permitOnly;
  53.         private AssemblyName m_assemblyName;
  54.         private byte[] m_serializedMethodInfo;
  55.         private string m_strMethodInfo;
  56.         private SecurityZone m_zone;
  57.         private string m_url;
  58.        
  59.         private const string ActionName = "Action";
  60.         private const string FirstPermissionThatFailedName = "FirstPermissionThatFailed";
  61.         private const string DemandedName = "Demanded";
  62.         private const string GrantedSetName = "GrantedSet";
  63.         private const string RefusedSetName = "RefusedSet";
  64.         private const string DeniedName = "Denied";
  65.         private const string PermitOnlyName = "PermitOnly";
  66.         private const string Assembly_Name = "Assembly";
  67.         private const string MethodName_Serialized = "Method";
  68.         private const string MethodName_String = "Method_String";
  69.         private const string ZoneName = "Zone";
  70.         private const string UrlName = "Url";
  71.        
  72.         static internal string GetResString(string sResourceName)
  73.         {
  74.             PermissionSet.s_fullTrust.Assert();
  75.             return Environment.GetResourceString(sResourceName);
  76.         }
  77.        
  78.         static internal Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, object demand, IPermission permThatFailed)
  79.         {
  80.             // See if we need to throw a HostProtectionException instead
  81.             HostProtectionPermission hostProtectionPerm = permThatFailed as HostProtectionPermission;
  82.             if (hostProtectionPerm != null)
  83.                 return new HostProtectionException(GetResString("HostProtection_HostProtection"), HostProtectionPermission.protectedResources, hostProtectionPerm.Resources);
  84.            
  85.             // Produce relevant strings
  86.             string message = "";
  87.             MethodInfo method = null;
  88.             try {
  89.                 if (granted == null && refused == null && demand == null) {
  90.                     message = GetResString("Security_NoAPTCA");
  91.                 }
  92.                 else {
  93.                     if (demand != null && demand is IPermission)
  94.                         message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), demand.GetType().AssemblyQualifiedName);
  95.                     else if (permThatFailed != null)
  96.                         message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), permThatFailed.GetType().AssemblyQualifiedName);
  97.                     else
  98.                         message = GetResString("Security_GenericNoType");
  99.                 }
  100.                
  101.                 method = SecurityRuntime.GetMethodInfo(rmh);
  102.             }
  103.             catch (Exception e) {
  104.                 // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort). (We shouldn't do a BCLDebug.Assert in this case or it will lock up the thread.)
  105.                 if (e is System.Threading.ThreadAbortException)
  106.                     throw;
  107.             }
  108.            
  109.             /*            catch(System.Threading.ThreadAbortException)
  110.             {
  111.                 // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort).  (We shouldn't do a BCLDebug.Assert in this case or it will lock up the thread.)
  112.                 throw;
  113.             }
  114.             catch
  115.             {
  116.             }
  117. */           
  118.             // make the exception object
  119. return new SecurityException(message, asmName, granted, refused, method, action, demand, permThatFailed, asmEvidence);
  120.         }
  121.        
  122.         private static byte[] ObjectToByteArray(object obj)
  123.         {
  124.             if (obj == null)
  125.                 return null;
  126.             MemoryStream stream = new MemoryStream();
  127.             BinaryFormatter formatter = new BinaryFormatter();
  128.             try {
  129.                 formatter.Serialize(stream, obj);
  130.                 byte[] array = stream.ToArray();
  131.                 return array;
  132.             }
  133.             catch (NotSupportedException) {
  134.                 // Serialization of certain methods is not supported (namely
  135.                 // global methods, since they have no representation outside of
  136.                 // a module scope).
  137.                 return null;
  138.             }
  139.         }
  140.        
  141.         private static object ByteArrayToObject(byte[] array)
  142.         {
  143.             if (array == null || array.Length == 0)
  144.                 return null;
  145.             MemoryStream stream = new MemoryStream(array);
  146.             BinaryFormatter formatter = new BinaryFormatter();
  147.             object obj = formatter.Deserialize(stream);
  148.             return obj;
  149.         }
  150.        
  151.         public SecurityException() : base(GetResString("Arg_SecurityException"))
  152.         {
  153.             SetErrorCode(System.__HResults.COR_E_SECURITY);
  154.         }
  155.        
  156.         public SecurityException(string message) : base(message)
  157.         {
  158.             // This is the constructor that gets called if you Assert but don't have permission to Assert. (So don't assert in here.)
  159.             SetErrorCode(System.__HResults.COR_E_SECURITY);
  160.         }
  161.        
  162.         public SecurityException(string message, Type type) : base(message)
  163.         {
  164.             PermissionSet.s_fullTrust.Assert();
  165.             SetErrorCode(System.__HResults.COR_E_SECURITY);
  166.             m_typeOfPermissionThatFailed = type;
  167.         }
  168.        
  169.         // *** Don't use this constructor internally ***
  170.         public SecurityException(string message, Type type, string state) : base(message)
  171.         {
  172.             PermissionSet.s_fullTrust.Assert();
  173.             SetErrorCode(System.__HResults.COR_E_SECURITY);
  174.             m_typeOfPermissionThatFailed = type;
  175.             m_demanded = state;
  176.         }
  177.        
  178.         public SecurityException(string message, Exception inner) : base(message, inner)
  179.         {
  180.             SetErrorCode(System.__HResults.COR_E_SECURITY);
  181.         }
  182.        
  183.         // *** Don't use this constructor internally ***
  184.         internal SecurityException(PermissionSet grantedSetObj, PermissionSet refusedSetObj) : base(GetResString("Arg_SecurityException"))
  185.         {
  186.             PermissionSet.s_fullTrust.Assert();
  187.             SetErrorCode(System.__HResults.COR_E_SECURITY);
  188.             if (grantedSetObj != null)
  189.                 m_granted = grantedSetObj.ToXml().ToString();
  190.             if (refusedSetObj != null)
  191.                 m_refused = refusedSetObj.ToXml().ToString();
  192.         }
  193.        
  194.         // *** Don't use this constructor internally ***
  195.         internal SecurityException(string message, PermissionSet grantedSetObj, PermissionSet refusedSetObj) : base(message)
  196.         {
  197.             PermissionSet.s_fullTrust.Assert();
  198.             SetErrorCode(System.__HResults.COR_E_SECURITY);
  199.             if (grantedSetObj != null)
  200.                 m_granted = grantedSetObj.ToXml().ToString();
  201.             if (refusedSetObj != null)
  202.                 m_refused = refusedSetObj.ToXml().ToString();
  203.         }
  204.        
  205.         protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context)
  206.         {
  207.             if (info == null)
  208.                 throw new ArgumentNullException("info");
  209.            
  210.             try {
  211.                 m_action = (SecurityAction)info.GetValue(ActionName, typeof(SecurityAction));
  212.                 m_permissionThatFailed = (string)info.GetValueNoThrow(FirstPermissionThatFailedName, typeof(string));
  213.                 m_demanded = (string)info.GetValueNoThrow(DemandedName, typeof(string));
  214.                 m_granted = (string)info.GetValueNoThrow(GrantedSetName, typeof(string));
  215.                 m_refused = (string)info.GetValueNoThrow(RefusedSetName, typeof(string));
  216.                 m_denied = (string)info.GetValueNoThrow(DeniedName, typeof(string));
  217.                 m_permitOnly = (string)info.GetValueNoThrow(PermitOnlyName, typeof(string));
  218.                 m_assemblyName = (AssemblyName)info.GetValueNoThrow(Assembly_Name, typeof(AssemblyName));
  219.                 m_serializedMethodInfo = (byte[])info.GetValueNoThrow(MethodName_Serialized, typeof(byte[]));
  220.                 m_strMethodInfo = (string)info.GetValueNoThrow(MethodName_String, typeof(string));
  221.                 m_zone = (SecurityZone)info.GetValue(ZoneName, typeof(SecurityZone));
  222.                 m_url = (string)info.GetValueNoThrow(UrlName, typeof(string));
  223.             }
  224.             catch {
  225.                 m_action = 0;
  226.                 m_permissionThatFailed = "";
  227.                 m_demanded = "";
  228.                 m_granted = "";
  229.                 m_refused = "";
  230.                 m_denied = "";
  231.                 m_permitOnly = "";
  232.                 m_assemblyName = null;
  233.                 m_serializedMethodInfo = null;
  234.                 m_strMethodInfo = null;
  235.                 m_zone = SecurityZone.NoZone;
  236.                 m_url = "";
  237.             }
  238.         }
  239.        
  240.         // ------------------------------------------
  241.         // | For failures due to insufficient grant |
  242.         // ------------------------------------------
  243.         public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, object demanded, IPermission permThatFailed, Evidence evidence) : base(message)
  244.         {
  245.             PermissionSet.s_fullTrust.Assert();
  246.             SetErrorCode(System.__HResults.COR_E_SECURITY);
  247.             Action = action;
  248.             if (permThatFailed != null)
  249.                 m_typeOfPermissionThatFailed = permThatFailed.GetType();
  250.             FirstPermissionThatFailed = permThatFailed;
  251.             Demanded = demanded;
  252.             m_granted = (grant == null ? "" : grant.ToXml().ToString());
  253.             m_refused = (refused == null ? "" : refused.ToXml().ToString());
  254.             m_denied = "";
  255.             m_permitOnly = "";
  256.             m_assemblyName = assemblyName;
  257.             Method = method;
  258.             m_url = "";
  259.             m_zone = SecurityZone.NoZone;
  260.             if (evidence != null) {
  261.                 Url url = (Url)evidence.FindType(typeof(Url));
  262.                 if (url != null)
  263.                     m_url = url.GetURLString().ToString();
  264.                 Zone zone = (Zone)evidence.FindType(typeof(Zone));
  265.                 if (zone != null)
  266.                     m_zone = zone.SecurityZone;
  267.             }
  268.             m_debugString = this.ToString(true, false);
  269.         }
  270.        
  271.         // ------------------------------------------
  272.         // | For failures due to deny or PermitOnly |
  273.         // ------------------------------------------
  274.         public SecurityException(string message, object deny, object permitOnly, MethodInfo method, object demanded, IPermission permThatFailed) : base(message)
  275.         {
  276.             PermissionSet.s_fullTrust.Assert();
  277.             SetErrorCode(System.__HResults.COR_E_SECURITY);
  278.             Action = SecurityAction.Demand;
  279.             if (permThatFailed != null)
  280.                 m_typeOfPermissionThatFailed = permThatFailed.GetType();
  281.             FirstPermissionThatFailed = permThatFailed;
  282.             Demanded = demanded;
  283.             m_granted = "";
  284.             m_refused = "";
  285.             DenySetInstance = deny;
  286.             PermitOnlySetInstance = permitOnly;
  287.             m_assemblyName = null;
  288.             Method = method;
  289.             m_zone = SecurityZone.NoZone;
  290.             m_url = "";
  291.             m_debugString = this.ToString(true, false);
  292.         }
  293.        
  294.        
  295.        
  296.        
  297.        
  298.        
  299.        
  300.        
  301.        
  302.        
  303.        
  304.         [System.Runtime.InteropServices.ComVisible(false)]
  305.         public SecurityAction Action {
  306.             get { return m_action; }
  307.            
  308.             set { m_action = value; }
  309.         }
  310.        
  311.         public Type PermissionType {
  312.             get {
  313.                 if (m_typeOfPermissionThatFailed == null) {
  314.                     object ob = XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed);
  315.                     if (ob == null)
  316.                         ob = XMLUtil.XmlStringToSecurityObject(m_demanded);
  317.                     if (ob != null)
  318.                         m_typeOfPermissionThatFailed = ob.GetType();
  319.                 }
  320.                 return m_typeOfPermissionThatFailed;
  321.             }
  322.            
  323.             set { m_typeOfPermissionThatFailed = value; }
  324.         }
  325.        
  326.         public IPermission FirstPermissionThatFailed {
  327.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  328.             get { return (IPermission)XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed); }
  329.            
  330.             set { m_permissionThatFailed = XMLUtil.SecurityObjectToXmlString(value); }
  331.         }
  332.        
  333.         public string PermissionState {
  334.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  335.             get { return m_demanded; }
  336.            
  337.             set { m_demanded = value; }
  338.         }
  339.        
  340.         [System.Runtime.InteropServices.ComVisible(false)]
  341.         public object Demanded {
  342.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  343.             get { return XMLUtil.XmlStringToSecurityObject(m_demanded); }
  344.            
  345.             set { m_demanded = XMLUtil.SecurityObjectToXmlString(value); }
  346.         }
  347.        
  348.         public string GrantedSet {
  349.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  350.             get { return m_granted; }
  351.            
  352.             set { m_granted = value; }
  353.         }
  354.        
  355.         public string RefusedSet {
  356.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  357.             get { return m_refused; }
  358.            
  359.             set { m_refused = value; }
  360.         }
  361.        
  362.         [System.Runtime.InteropServices.ComVisible(false)]
  363.         public object DenySetInstance {
  364.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  365.             get { return XMLUtil.XmlStringToSecurityObject(m_denied); }
  366.            
  367.             set { m_denied = XMLUtil.SecurityObjectToXmlString(value); }
  368.         }
  369.        
  370.         [System.Runtime.InteropServices.ComVisible(false)]
  371.         public object PermitOnlySetInstance {
  372.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  373.             get { return XMLUtil.XmlStringToSecurityObject(m_permitOnly); }
  374.            
  375.             set { m_permitOnly = XMLUtil.SecurityObjectToXmlString(value); }
  376.         }
  377.        
  378.         [System.Runtime.InteropServices.ComVisible(false)]
  379.         public AssemblyName FailedAssemblyInfo {
  380.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  381.             get { return m_assemblyName; }
  382.            
  383.             set { m_assemblyName = value; }
  384.         }
  385.        
  386.         private MethodInfo getMethod()
  387.         {
  388.             return (MethodInfo)ByteArrayToObject(m_serializedMethodInfo);
  389.         }
  390.        
  391.         [System.Runtime.InteropServices.ComVisible(false)]
  392.         public MethodInfo Method {
  393.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  394.             get { return getMethod(); }
  395.            
  396.             set {
  397.                 RuntimeMethodInfo m = value as RuntimeMethodInfo;
  398.                 m_serializedMethodInfo = ObjectToByteArray(m);
  399.                 if (m != null) {
  400.                     m_strMethodInfo = m.ToString();
  401.                 }
  402.             }
  403.         }
  404.        
  405.         public SecurityZone Zone {
  406.             get { return m_zone; }
  407.            
  408.             set { m_zone = value; }
  409.         }
  410.        
  411.         public string Url {
  412.             [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
  413.             get { return m_url; }
  414.            
  415.             set { m_url = value; }
  416.         }
  417.        
  418.         private void ToStringHelper(StringBuilder sb, string resourceString, object attr)
  419.         {
  420.             if (attr == null)
  421.                 return;
  422.             string attrString = attr as string;
  423.             if (attrString == null)
  424.                 attrString = attr.ToString();
  425.             if (attrString.Length == 0)
  426.                 return;
  427.             sb.Append(Environment.NewLine);
  428.             sb.Append(GetResString(resourceString));
  429.             sb.Append(Environment.NewLine);
  430.             sb.Append(attrString);
  431.         }
  432.        
  433.         private string ToString(bool includeSensitiveInfo, bool includeBaseInfo)
  434.         {
  435.             PermissionSet.s_fullTrust.Assert();
  436.             StringBuilder sb = new StringBuilder();
  437.            
  438.             if (includeBaseInfo)
  439.                 sb.Append(base.ToString());
  440.             if (Action > 0)
  441.                 ToStringHelper(sb, "Security_Action", Action);
  442.             ToStringHelper(sb, "Security_TypeFirstPermThatFailed", PermissionType);
  443.             if (includeSensitiveInfo) {
  444.                 ToStringHelper(sb, "Security_FirstPermThatFailed", m_permissionThatFailed);
  445.                 ToStringHelper(sb, "Security_Demanded", m_demanded);
  446.                 ToStringHelper(sb, "Security_GrantedSet", m_granted);
  447.                 ToStringHelper(sb, "Security_RefusedSet", m_refused);
  448.                 ToStringHelper(sb, "Security_Denied", m_denied);
  449.                 ToStringHelper(sb, "Security_PermitOnly", m_permitOnly);
  450.                 ToStringHelper(sb, "Security_Assembly", m_assemblyName);
  451.                 ToStringHelper(sb, "Security_Method", m_strMethodInfo);
  452.             }
  453.             if (m_zone != SecurityZone.NoZone)
  454.                 ToStringHelper(sb, "Security_Zone", m_zone);
  455.             if (includeSensitiveInfo)
  456.                 ToStringHelper(sb, "Security_Url", m_url);
  457.             return sb.ToString();
  458.         }
  459.        
  460.         private bool CanAccessSensitiveInfo()
  461.         {
  462.             bool retVal = false;
  463.             try {
  464.                 new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy).Demand();
  465.                 retVal = true;
  466.             }
  467.             catch (SecurityException) {
  468.             }
  469.             return retVal;
  470.         }
  471.        
  472.         public override string ToString()
  473.         {
  474.             return ToString(CanAccessSensitiveInfo(), true);
  475.         }
  476.        
  477.         [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
  478.         public override void GetObjectData(SerializationInfo info, StreamingContext context)
  479.         {
  480.             if (info == null)
  481.                 throw new ArgumentNullException("info");
  482.            
  483.             base.GetObjectData(info, context);
  484.            
  485.             info.AddValue(ActionName, m_action, typeof(SecurityAction));
  486.             info.AddValue(FirstPermissionThatFailedName, m_permissionThatFailed, typeof(string));
  487.             info.AddValue(DemandedName, m_demanded, typeof(string));
  488.             info.AddValue(GrantedSetName, m_granted, typeof(string));
  489.             info.AddValue(RefusedSetName, m_refused, typeof(string));
  490.             info.AddValue(DeniedName, m_denied, typeof(string));
  491.             info.AddValue(PermitOnlyName, m_permitOnly, typeof(string));
  492.             info.AddValue(Assembly_Name, m_assemblyName, typeof(AssemblyName));
  493.             info.AddValue(MethodName_Serialized, m_serializedMethodInfo, typeof(byte[]));
  494.             info.AddValue(MethodName_String, m_strMethodInfo, typeof(string));
  495.             info.AddValue(ZoneName, m_zone, typeof(SecurityZone));
  496.             info.AddValue(UrlName, m_url, typeof(string));
  497.         }
  498.     }
  499. }

Developer Fusion