2 // System.Security.SecurityManager.cs
5 // Nick Drochak(ndrochak@gol.com)
6 // Sebastien Pouliot <sebastien@ximian.com>
9 // Portions (C) 2004 Motus Technologies Inc. (http://www.motus.com)
10 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Collections;
35 using System.Diagnostics;
36 using System.Globalization;
38 using System.Reflection;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security.Permissions;
42 using System.Security.Policy;
47 namespace System.Security {
49 // Must match MonoDeclSecurityActions in /mono/metadata/reflection.h
50 internal struct RuntimeDeclSecurityActions {
51 public RuntimeDeclSecurityEntry cas;
52 public RuntimeDeclSecurityEntry noncas;
53 public RuntimeDeclSecurityEntry choice;
57 public static class SecurityManager {
58 private static object _lockObject;
59 private static ArrayList _hierarchy;
60 private static IPermission _unmanagedCode;
61 private static Hashtable _declsecCache;
62 private static PolicyLevel _level;
64 static SecurityManager ()
67 // http://msdn.microsoft.com/library/en-us/dnaskdr/html/askgui06032003.asp?frame=true
68 _lockObject = new object ();
73 extern public static bool CheckExecutionRights {
74 [MethodImplAttribute (MethodImplOptions.InternalCall)]
77 [MethodImplAttribute (MethodImplOptions.InternalCall)]
78 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
82 [Obsolete ("The security manager cannot be turned off on MS runtime")]
83 extern public static bool SecurityEnabled {
84 [MethodImplAttribute (MethodImplOptions.InternalCall)]
87 [MethodImplAttribute (MethodImplOptions.InternalCall)]
88 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
92 internal static bool CheckElevatedPermissions ()
94 return true; // always true outside Moonlight
97 [Conditional ("MOONLIGHT")]
98 internal static void EnsureElevatedPermissions ()
100 // do nothing outside of Moonlight
105 // NOTE: This method doesn't show in the class library status page because
106 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
108 // FIXME works for fulltrust (empty), documentation doesn't really make sense, type wise
109 [MonoTODO ("CAS support is experimental (and unsupported). This method only works in FullTrust.")]
110 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey = "0x00000000000000000400000000000000")]
111 public static void GetZoneAndOrigin (out ArrayList zone, out ArrayList origin)
113 zone = new ArrayList ();
114 origin = new ArrayList ();
117 public static bool IsGranted (IPermission perm)
121 if (!SecurityEnabled)
125 // - Only check the caller (no stack walk required)
126 // - Not affected by overrides (like Assert, Deny and PermitOnly)
127 // - calls IsSubsetOf even for non CAS permissions
128 // (i.e. it does call Demand so any code there won't be executed)
129 // with 2.0 identity permission are unrestrictable
130 return IsGranted (Assembly.GetCallingAssembly (), perm);
133 // note: in 2.0 *all* permissions (including identity permissions) support unrestricted
134 internal static bool IsGranted (Assembly a, IPermission perm)
136 PermissionSet granted = a.GrantedPermissionSet;
137 if ((granted != null) && !granted.IsUnrestricted ()) {
138 CodeAccessPermission grant = (CodeAccessPermission) granted.GetPermission (perm.GetType ());
139 if (!perm.IsSubsetOf (grant)) {
144 PermissionSet denied = a.DeniedPermissionSet;
145 if ((denied != null) && !denied.IsEmpty ()) {
146 if (denied.IsUnrestricted ())
148 CodeAccessPermission refuse = (CodeAccessPermission) a.DeniedPermissionSet.GetPermission (perm.GetType ());
149 if ((refuse != null) && perm.IsSubsetOf (refuse))
155 internal static IPermission CheckPermissionSet (Assembly a, PermissionSet ps, bool noncas)
160 foreach (IPermission p in ps) {
161 // note: this may contains non CAS permissions
162 if ((!noncas) && (p is CodeAccessPermission)) {
163 if (!IsGranted (a, p))
166 // but non-CAS will throw on failure...
170 catch (SecurityException) {
179 internal static IPermission CheckPermissionSet (AppDomain ad, PermissionSet ps)
181 if ((ps == null) || ps.IsEmpty ())
184 PermissionSet granted = ad.GrantedPermissionSet;
187 if (granted.IsUnrestricted ())
189 if (ps.IsUnrestricted ())
190 return new SecurityPermission (SecurityPermissionFlag.NoFlags);
192 foreach (IPermission p in ps) {
193 if (p is CodeAccessPermission) {
194 CodeAccessPermission grant = (CodeAccessPermission) granted.GetPermission (p.GetType ());
196 if (!granted.IsUnrestricted () || !(p is IUnrestrictedPermission)) {
197 if (!p.IsSubsetOf (null))
200 } else if (!p.IsSubsetOf (grant)) {
204 // but non-CAS will throw on failure...
208 catch (SecurityException) {
217 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
218 public static PolicyLevel LoadPolicyLevelFromFile (string path, PolicyLevelType type)
221 throw new ArgumentNullException ("path");
223 PolicyLevel pl = null;
225 pl = new PolicyLevel (type.ToString (), type);
226 pl.LoadFromFile (path);
228 catch (Exception e) {
229 throw new ArgumentException (Locale.GetText ("Invalid policy XML"), e);
234 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
235 public static PolicyLevel LoadPolicyLevelFromString (string str, PolicyLevelType type)
238 throw new ArgumentNullException ("str");
240 PolicyLevel pl = null;
242 pl = new PolicyLevel (type.ToString (), type);
243 pl.LoadFromString (str);
245 catch (Exception e) {
246 throw new ArgumentException (Locale.GetText ("Invalid policy XML"), e);
251 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
252 public static IEnumerator PolicyHierarchy ()
257 public static PermissionSet ResolvePolicy (Evidence evidence)
259 // no evidence, no permission
260 if (evidence == null)
261 return new PermissionSet (PermissionState.None);
263 PermissionSet ps = null;
264 // Note: can't call PolicyHierarchy since ControlPolicy isn't required to resolve policies
265 IEnumerator ple = Hierarchy;
266 while (ple.MoveNext ()) {
267 PolicyLevel pl = (PolicyLevel) ple.Current;
268 if (ResolvePolicyLevel (ref ps, pl, evidence)) {
269 break; // i.e. PolicyStatementAttribute.LevelFinal
273 ResolveIdentityPermissions (ps, evidence);
278 [MonoTODO ("(2.0) more tests are needed")]
279 public static PermissionSet ResolvePolicy (Evidence[] evidences)
281 if ((evidences == null) || (evidences.Length == 0) ||
282 ((evidences.Length == 1) && (evidences [0].Count == 0))) {
283 return new PermissionSet (PermissionState.None);
286 // probably not optimal
287 PermissionSet ps = ResolvePolicy (evidences [0]);
288 for (int i=1; i < evidences.Length; i++) {
289 ps = ps.Intersect (ResolvePolicy (evidences [i]));
294 public static PermissionSet ResolveSystemPolicy (Evidence evidence)
296 // no evidence, no permission
297 if (evidence == null)
298 return new PermissionSet (PermissionState.None);
300 // Note: can't call PolicyHierarchy since ControlPolicy isn't required to resolve policies
301 PermissionSet ps = null;
302 IEnumerator ple = Hierarchy;
303 while (ple.MoveNext ()) {
304 PolicyLevel pl = (PolicyLevel) ple.Current;
305 if (pl.Type == PolicyLevelType.AppDomain)
307 if (ResolvePolicyLevel (ref ps, pl, evidence))
308 break; // i.e. PolicyStatementAttribute.LevelFinal
311 ResolveIdentityPermissions (ps, evidence);
315 static private SecurityPermission _execution = new SecurityPermission (SecurityPermissionFlag.Execution);
317 public static PermissionSet ResolvePolicy (Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, out PermissionSet denied)
319 PermissionSet resolved = ResolvePolicy (evidence);
320 // do we have the minimal permission requested by the assembly ?
321 if ((reqdPset != null) && !reqdPset.IsSubsetOf (resolved)) {
322 throw new PolicyException (Locale.GetText (
323 "Policy doesn't grant the minimal permissions required to execute the assembly."));
326 // do we check for execution rights ?
327 if (CheckExecutionRights) {
328 bool execute = false;
329 // an empty permissionset doesn't include Execution
330 if (resolved != null) {
331 // unless we have "Full Trust"...
332 if (resolved.IsUnrestricted ()) {
335 // ... we need to find a SecurityPermission
336 IPermission security = resolved.GetPermission (typeof (SecurityPermission));
337 execute = _execution.IsSubsetOf (security);
342 throw new PolicyException (Locale.GetText (
343 "Policy doesn't grant the right to execute the assembly."));
351 public static IEnumerator ResolvePolicyGroups (Evidence evidence)
353 if (evidence == null)
354 throw new ArgumentNullException ("evidence");
356 ArrayList al = new ArrayList ();
357 // Note: can't call PolicyHierarchy since ControlPolicy isn't required to resolve policies
358 IEnumerator ple = Hierarchy;
359 while (ple.MoveNext ()) {
360 PolicyLevel pl = (PolicyLevel) ple.Current;
361 CodeGroup cg = pl.ResolveMatchingCodeGroups (evidence);
364 return al.GetEnumerator ();
367 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
368 public static void SavePolicy ()
370 IEnumerator e = Hierarchy;
371 while (e.MoveNext ()) {
372 PolicyLevel level = (e.Current as PolicyLevel);
377 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
378 public static void SavePolicyLevel (PolicyLevel level)
380 // Yes this will throw a NullReferenceException, just like MS (see FDBK13121)
384 // private/internal stuff
386 private static IEnumerator Hierarchy {
389 if (_hierarchy == null)
390 InitializePolicyHierarchy ();
392 return _hierarchy.GetEnumerator ();
396 private static void InitializePolicyHierarchy ()
398 string machinePolicyPath = Path.GetDirectoryName (Environment.GetMachineConfigPath ());
399 // note: use InternalGetFolderPath to avoid recursive policy initialization
400 string userPolicyPath = Path.Combine (Environment.InternalGetFolderPath (Environment.SpecialFolder.ApplicationData), "mono");
402 PolicyLevel enterprise = new PolicyLevel ("Enterprise", PolicyLevelType.Enterprise);
404 enterprise.LoadFromFile (Path.Combine (machinePolicyPath, "enterprisesec.config"));
406 PolicyLevel machine = new PolicyLevel ("Machine", PolicyLevelType.Machine);
408 machine.LoadFromFile (Path.Combine (machinePolicyPath, "security.config"));
410 PolicyLevel user = new PolicyLevel ("User", PolicyLevelType.User);
412 user.LoadFromFile (Path.Combine (userPolicyPath, "security.config"));
414 ArrayList al = new ArrayList ();
419 _hierarchy = ArrayList.Synchronized (al);
423 internal static bool ResolvePolicyLevel (ref PermissionSet ps, PolicyLevel pl, Evidence evidence)
425 PolicyStatement pst = pl.Resolve (evidence);
428 // only for initial (first) policy level processed
429 ps = pst.PermissionSet;
431 ps = ps.Intersect (pst.PermissionSet);
433 // null is equals to None - exist that null can throw NullReferenceException ;-)
434 ps = new PermissionSet (PermissionState.None);
438 if ((pst.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal)
444 internal static void ResolveIdentityPermissions (PermissionSet ps, Evidence evidence)
446 // in 2.0 identity permissions can now be unrestricted
447 if (ps.IsUnrestricted ())
450 // Only host evidence are used for policy resolution
451 IEnumerator ee = evidence.GetHostEnumerator ();
452 while (ee.MoveNext ()) {
453 IIdentityPermissionFactory ipf = (ee.Current as IIdentityPermissionFactory);
455 IPermission p = ipf.CreateIdentityPermission (evidence);
456 ps.AddPermission (p);
461 internal static PolicyLevel ResolvingPolicyLevel {
462 get { return _level; }
463 set { _level = value; }
466 internal static PermissionSet Decode (IntPtr permissions, int length)
468 // Permission sets from the runtime (declarative security) can be cached
469 // for performance as they can never change (i.e. they are read-only).
470 PermissionSet ps = null;
473 if (_declsecCache == null) {
474 _declsecCache = new Hashtable ();
477 object key = (object) (int) permissions;
478 ps = (PermissionSet) _declsecCache [key];
480 // create permissionset and add it to the cache
481 byte[] data = new byte [length];
482 Marshal.Copy (permissions, data, 0, length);
484 ps.DeclarativeSecurity = true;
485 _declsecCache.Add (key, ps);
491 internal static PermissionSet Decode (byte[] encodedPermissions)
493 if ((encodedPermissions == null) || (encodedPermissions.Length < 1))
494 throw new SecurityException ("Invalid metadata format.");
496 switch (encodedPermissions [0]) {
498 // Fx 1.0/1.1 declarative security permissions metadata is in Unicode-encoded XML
499 string xml = Encoding.Unicode.GetString (encodedPermissions);
500 return new PermissionSet (xml);
502 // Fx 2.0 are encoded "somewhat, but not enough, like" custom attributes
503 // note: we still support the older format!
504 return PermissionSet.CreateFromBinaryFormat (encodedPermissions);
506 throw new SecurityException (Locale.GetText ("Unknown metadata format."));
510 private static IPermission UnmanagedCode {
513 if (_unmanagedCode == null)
514 _unmanagedCode = new SecurityPermission (SecurityPermissionFlag.UnmanagedCode);
516 return _unmanagedCode;
520 // security check when using reflection
522 [MethodImplAttribute(MethodImplOptions.InternalCall)]
523 private static unsafe extern bool GetLinkDemandSecurity (MethodBase method, RuntimeDeclSecurityActions *cdecl, RuntimeDeclSecurityActions *mdecl);
525 // When using reflection LinkDemand are promoted to full Demand (i.e. stack walk)
526 internal unsafe static void ReflectedLinkDemandInvoke (MethodBase mb)
528 RuntimeDeclSecurityActions klass;
529 RuntimeDeclSecurityActions method;
531 if (!GetLinkDemandSecurity (mb, &klass, &method))
534 PermissionSet ps = null;
536 if (klass.cas.size > 0) {
537 ps = Decode (klass.cas.blob, klass.cas.size);
539 if (klass.noncas.size > 0) {
540 PermissionSet p = Decode (klass.noncas.blob, klass.noncas.size);
541 ps = (ps == null) ? p : ps.Union (p);
544 if (method.cas.size > 0) {
545 PermissionSet p = Decode (method.cas.blob, method.cas.size);
546 ps = (ps == null) ? p : ps.Union (p);
548 if (method.noncas.size > 0) {
549 PermissionSet p = Decode (method.noncas.blob, method.noncas.size);
550 ps = (ps == null) ? p : ps.Union (p);
553 // in this case we union-ed the permission sets because we want to do
554 // a single stack walk (not up to 4).
559 internal unsafe static bool ReflectedLinkDemandQuery (MethodBase mb)
561 RuntimeDeclSecurityActions klass;
562 RuntimeDeclSecurityActions method;
564 if (!GetLinkDemandSecurity (mb, &klass, &method))
567 return LinkDemand (mb.ReflectedType.Assembly, &klass, &method);
570 private unsafe static bool LinkDemand (Assembly a, RuntimeDeclSecurityActions *klass, RuntimeDeclSecurityActions *method)
573 PermissionSet ps = null;
575 if (klass->cas.size > 0) {
576 ps = Decode (klass->cas.blob, klass->cas.size);
577 result = (SecurityManager.CheckPermissionSet (a, ps, false) == null);
579 if (result && (klass->noncas.size > 0)) {
580 ps = Decode (klass->noncas.blob, klass->noncas.size);
581 result = (SecurityManager.CheckPermissionSet (a, ps, true) == null);
584 if (result && (method->cas.size > 0)) {
585 ps = Decode (method->cas.blob, method->cas.size);
586 result = (SecurityManager.CheckPermissionSet (a, ps, false) == null);
588 if (result && (method->noncas.size > 0)) {
589 ps = Decode (method->noncas.blob, method->noncas.size);
590 result = (SecurityManager.CheckPermissionSet (a, ps, true) == null);
594 catch (SecurityException) {
599 #pragma warning disable 169
600 private static bool LinkDemandFullTrust (Assembly a)
602 // FullTrust is immutable (and means Unrestricted)
603 // so we can skip the subset operations and jump to IsUnrestricted.
604 PermissionSet granted = a.GrantedPermissionSet;
605 if ((granted != null) && !granted.IsUnrestricted ())
608 PermissionSet denied = a.DeniedPermissionSet;
609 if ((denied != null) && !denied.IsEmpty ())
615 private static bool LinkDemandUnmanaged (Assembly a)
617 // note: we know that UnmanagedCode (SecurityPermission) implements IUnrestrictedPermission
618 return IsGranted (a, UnmanagedCode);
621 // we try to provide as much details as possible to help debugging
622 private static void LinkDemandSecurityException (int securityViolation, IntPtr methodHandle)
624 RuntimeMethodHandle runtimeHandle = new RuntimeMethodHandle (methodHandle);
625 MethodInfo method = (MethodInfo)(MethodBase.GetMethodFromHandle (runtimeHandle));
626 Assembly a = method.DeclaringType.Assembly;
628 string message = null;
629 AssemblyName an = null;
630 PermissionSet granted = null;
631 PermissionSet refused = null;
632 object demanded = null;
633 IPermission failed = null;
636 an = a.UnprotectedGetName ();
637 granted = a.GrantedPermissionSet;
638 refused = a.DeniedPermissionSet;
641 switch (securityViolation) {
642 case 1: // MONO_JIT_LINKDEMAND_PERMISSION
643 message = Locale.GetText ("Permissions refused to call this method.");
645 case 2: // MONO_JIT_LINKDEMAND_APTC
646 message = Locale.GetText ("Partially trusted callers aren't allowed to call into this assembly.");
647 demanded = (object) DefaultPolicies.FullTrust; // immutable
649 case 4: // MONO_JIT_LINKDEMAND_ECMA
650 message = Locale.GetText ("Calling internal calls is restricted to ECMA signed assemblies.");
652 case 8: // MONO_JIT_LINKDEMAND_PINVOKE
653 message = Locale.GetText ("Calling unmanaged code isn't allowed from this assembly.");
654 demanded = (object) _unmanagedCode;
655 failed = _unmanagedCode;
658 message = Locale.GetText ("JIT time LinkDemand failed.");
662 throw new SecurityException (message, an, granted, refused, method, SecurityAction.LinkDemand, demanded, failed, null);
665 private static void InheritanceDemandSecurityException (int securityViolation, Assembly a, Type t, MethodInfo method)
667 string message = null;
668 AssemblyName an = null;
669 PermissionSet granted = null;
670 PermissionSet refused = null;
673 an = a.UnprotectedGetName ();
674 granted = a.GrantedPermissionSet;
675 refused = a.DeniedPermissionSet;
678 switch (securityViolation) {
679 case 1: // MONO_METADATA_INHERITANCEDEMAND_CLASS
680 message = String.Format (Locale.GetText ("Class inheritance refused for {0}."), t);
682 case 2: // MONO_METADATA_INHERITANCEDEMAND_CLASS
683 message = Locale.GetText ("Method override refused.");
686 message = Locale.GetText ("Load time InheritDemand failed.");
690 throw new SecurityException (message, an, granted, refused, method, SecurityAction.InheritanceDemand, null, null, null);
693 // called by the runtime when CoreCLR is enabled
695 private static void ThrowException (Exception ex)
700 // internal - get called by the class loader
703 // - class inheritance
704 // - method overrides
705 private unsafe static bool InheritanceDemand (AppDomain ad, Assembly a, RuntimeDeclSecurityActions *actions)
708 PermissionSet ps = null;
710 if (actions->cas.size > 0) {
711 ps = Decode (actions->cas.blob, actions->cas.size);
712 result = (SecurityManager.CheckPermissionSet (a, ps, false) == null);
714 // also check appdomain
715 result = (SecurityManager.CheckPermissionSet (ad, ps) == null);
718 if (actions->noncas.size > 0) {
719 ps = Decode (actions->noncas.blob, actions->noncas.size);
720 result = (SecurityManager.CheckPermissionSet (a, ps, true) == null);
722 // also check appdomain
723 result = (SecurityManager.CheckPermissionSet (ad, ps) == null);
728 catch (SecurityException) {
733 // internal - get called at JIT time
735 private static void DemandUnmanaged ()
737 UnmanagedCode.Demand ();
740 // internal - get called by JIT generated code
742 private static void InternalDemand (IntPtr permissions, int length)
744 PermissionSet ps = Decode (permissions, length);
748 private static void InternalDemandChoice (IntPtr permissions, int length)
750 throw new SecurityException ("SecurityAction.DemandChoice was removed from 2.0");
752 #pragma warning restore 169