2 // System.Security.Policy.PolicyLevel.cs
5 // Nick Drochak (ndrochak@gol.com)
6 // Duncan Mak (duncan@ximian.com)
7 // Sebastien Pouliot <sebastien@ximian.com>
9 // (C) 2001 Nick Drochak
10 // (C) 2003 Duncan Mak, Ximian Inc.
11 // Portions (C) 2004 Motus Technologies Inc. (http://www.motus.com)
12 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Collections; // for IList
35 using System.Globalization;
37 using System.Reflection;
38 using System.Runtime.InteropServices;
39 using System.Security.Permissions;
43 namespace System.Security.Policy {
49 public sealed class PolicyLevel {
52 CodeGroup root_code_group;
53 private ArrayList full_trust_assemblies;
54 private ArrayList named_permission_sets;
55 private string _location;
56 private PolicyLevelType _type;
57 private Hashtable fullNames;
58 private SecurityElement xml;
60 internal PolicyLevel (string label, PolicyLevelType type)
64 full_trust_assemblies = new ArrayList ();
65 named_permission_sets = new ArrayList ();
68 internal void LoadFromFile (string filename)
71 // check for policy file
72 if (!File.Exists (filename)) {
73 // if it doesn't exist use the default configuration (like Fx 2.0)
74 // ref: http://blogs.msdn.com/shawnfa/archive/2004/04/21/117833.aspx
75 string defcfg = filename + ".default";
76 if (File.Exists (defcfg)) {
77 // create policy from default file
78 File.Copy (defcfg, filename);
81 // load security policy configuration
82 if (File.Exists (filename)) {
83 using (StreamReader sr = File.OpenText (filename)) {
84 xml = FromString (sr.ReadToEnd ());
87 SecurityManager.ResolvingPolicyLevel = this;
91 SecurityManager.ResolvingPolicyLevel = this;
94 CreateDefaultFullTrustAssemblies ();
95 CreateDefaultNamedPermissionSets ();
96 CreateDefaultLevel (_type);
101 // this can fail in many ways including...
102 // * can't lookup policy (path discovery);
103 // * can't copy default file to policy
104 // * can't read policy file;
105 // * can't decode policy file
106 // * can't save hardcoded policy to filename
109 _location = filename;
113 internal void LoadFromString (string xml)
115 FromXml (FromString (xml));
118 private SecurityElement FromString (string xml)
120 SecurityParser parser = new SecurityParser ();
121 parser.LoadXml (xml);
122 // configuration / mscorlib / security / policy / PolicyLevel
123 SecurityElement configuration = parser.ToXml ();
124 if (configuration.Tag != "configuration")
125 throw new ArgumentException (Locale.GetText ("missing <configuration> root element"));
126 SecurityElement mscorlib = (SecurityElement) configuration.Children [0];
127 if (mscorlib.Tag != "mscorlib")
128 throw new ArgumentException (Locale.GetText ("missing <mscorlib> tag"));
129 SecurityElement security = (SecurityElement) mscorlib.Children [0];
130 if (security.Tag != "security")
131 throw new ArgumentException (Locale.GetText ("missing <security> tag"));
132 SecurityElement policy = (SecurityElement) security.Children [0];
133 if (policy.Tag != "policy")
134 throw new ArgumentException (Locale.GetText ("missing <policy> tag"));
135 SecurityElement policyLevel = (SecurityElement) policy.Children [0];
142 [Obsolete ("All GACed assemblies are now fully trusted and all permissions now succeed on fully trusted code.")]
144 public IList FullTrustAssemblies {
145 get { return full_trust_assemblies; }
148 public string Label {
149 get { return label; }
152 public IList NamedPermissionSets {
153 get { return named_permission_sets; }
156 public CodeGroup RootCodeGroup {
157 get { return root_code_group; }
160 throw new ArgumentNullException ("value");
161 root_code_group = value;
165 public string StoreLocation {
166 get { return _location; }
171 public PolicyLevelType Type {
172 get { return _type; }
179 [Obsolete ("All GACed assemblies are now fully trusted and all permissions now succeed on fully trusted code.")]
181 public void AddFullTrustAssembly (StrongName sn)
184 throw new ArgumentNullException ("sn");
186 StrongNameMembershipCondition snMC = new StrongNameMembershipCondition(
187 sn.PublicKey, sn.Name, sn.Version);
189 AddFullTrustAssembly (snMC);
193 [Obsolete ("All GACed assemblies are now fully trusted and all permissions now succeed on fully trusted code.")]
195 public void AddFullTrustAssembly (StrongNameMembershipCondition snMC)
198 throw new ArgumentNullException ("snMC");
200 foreach (StrongNameMembershipCondition sn in full_trust_assemblies) {
201 if (sn.Equals (snMC)) {
202 throw new ArgumentException (Locale.GetText ("sn already has full trust."));
205 full_trust_assemblies.Add (snMC);
208 public void AddNamedPermissionSet (NamedPermissionSet permSet)
211 throw new ArgumentNullException ("permSet");
213 foreach (NamedPermissionSet n in named_permission_sets) {
214 if (permSet.Name == n.Name) {
215 throw new ArgumentException (
216 Locale.GetText ("This NamedPermissionSet is the same an existing NamedPermissionSet."));
219 named_permission_sets.Add (permSet.Copy ());
222 public NamedPermissionSet ChangeNamedPermissionSet (string name, PermissionSet pSet)
225 throw new ArgumentNullException ("name");
227 throw new ArgumentNullException ("pSet");
228 if (DefaultPolicies.ReservedNames.IsReserved (name))
229 throw new ArgumentException (Locale.GetText ("Reserved name"));
231 foreach (NamedPermissionSet n in named_permission_sets) {
232 if (name == n.Name) {
233 named_permission_sets.Remove (n);
234 AddNamedPermissionSet (new NamedPermissionSet (name, pSet));
238 throw new ArgumentException (Locale.GetText ("PermissionSet not found"));
241 public static PolicyLevel CreateAppDomainLevel ()
243 UnionCodeGroup cg = new UnionCodeGroup (new AllMembershipCondition (), new PolicyStatement (DefaultPolicies.FullTrust));
244 cg.Name = "All_Code";
245 PolicyLevel pl = new PolicyLevel ("AppDomain", PolicyLevelType.AppDomain);
246 pl.RootCodeGroup = cg;
252 public void FromXml (SecurityElement e)
255 throw new ArgumentNullException ("e");
256 // MS doesn't throw an exception for this case
257 // if (e.Tag != "PolicyLevel")
258 // throw new ArgumentException (Locale.GetText ("Invalid XML"));
260 SecurityElement sc = e.SearchForChildByTag ("SecurityClasses");
261 if ((sc != null) && (sc.Children != null) && (sc.Children.Count > 0)) {
262 fullNames = new Hashtable (sc.Children.Count);
263 foreach (SecurityElement se in sc.Children) {
264 fullNames.Add (se.Attributes ["Name"], se.Attributes ["Description"]);
268 SecurityElement fta = e.SearchForChildByTag ("FullTrustAssemblies");
269 if ((fta != null) && (fta.Children != null) && (fta.Children.Count > 0)) {
270 full_trust_assemblies.Clear ();
271 foreach (SecurityElement se in fta.Children) {
272 if (se.Tag != "IMembershipCondition")
273 throw new ArgumentException (Locale.GetText ("Invalid XML"));
274 string className = se.Attribute ("class");
275 if (className.IndexOf ("StrongNameMembershipCondition") < 0)
276 throw new ArgumentException (Locale.GetText ("Invalid XML - must be StrongNameMembershipCondition"));
277 // we directly use StrongNameMembershipCondition
278 full_trust_assemblies.Add (new StrongNameMembershipCondition (se));
282 SecurityElement cg = e.SearchForChildByTag ("CodeGroup");
283 if ((cg != null) && (cg.Children != null) && (cg.Children.Count > 0)) {
284 root_code_group = CodeGroup.CreateFromXml (cg, this);
286 throw new ArgumentException (Locale.GetText ("Missing Root CodeGroup"));
289 SecurityElement nps = e.SearchForChildByTag ("NamedPermissionSets");
290 if ((nps != null) && (nps.Children != null) && (nps.Children.Count > 0)) {
291 named_permission_sets.Clear ();
292 foreach (SecurityElement se in nps.Children) {
293 NamedPermissionSet n = new NamedPermissionSet ();
296 named_permission_sets.Add (n);
301 public NamedPermissionSet GetNamedPermissionSet (string name)
304 throw new ArgumentNullException ("name");
306 foreach (NamedPermissionSet n in named_permission_sets) {
308 return (NamedPermissionSet) n.Copy ();
313 public void Recover ()
315 if (_location == null) {
316 string msg = Locale.GetText ("Only file based policies may be recovered.");
317 throw new PolicyException (msg);
320 string backup = _location + ".backup";
321 if (!File.Exists (backup)) {
322 string msg = Locale.GetText ("No policy backup exists.");
323 throw new PolicyException (msg);
327 File.Copy (backup, _location, true);
329 catch (Exception e) {
330 string msg = Locale.GetText ("Couldn't replace the policy file with it's backup.");
331 throw new PolicyException (msg, e);
336 [Obsolete ("All GACed assemblies are now fully trusted and all permissions now succeed on fully trusted code.")]
338 public void RemoveFullTrustAssembly (StrongName sn)
341 throw new ArgumentNullException ("sn");
343 StrongNameMembershipCondition s = new StrongNameMembershipCondition (sn.PublicKey, sn.Name, sn.Version);
344 RemoveFullTrustAssembly (s);
348 [Obsolete ("All GACed assemblies are now fully trusted and all permissions now succeed on fully trusted code.")]
350 public void RemoveFullTrustAssembly (StrongNameMembershipCondition snMC)
353 throw new ArgumentNullException ("snMC");
355 if (((IList) full_trust_assemblies).Contains (snMC))
356 ((IList) full_trust_assemblies).Remove (snMC);
359 throw new ArgumentException (
360 Locale.GetText ("sn does not have full trust."));
363 public NamedPermissionSet RemoveNamedPermissionSet (NamedPermissionSet permSet)
366 throw new ArgumentNullException ("permSet");
368 return RemoveNamedPermissionSet (permSet.Name);
371 public NamedPermissionSet RemoveNamedPermissionSet (string name)
374 throw new ArgumentNullException ("name");
375 if (DefaultPolicies.ReservedNames.IsReserved (name))
376 throw new ArgumentException (Locale.GetText ("Reserved name"));
378 foreach (NamedPermissionSet nps in named_permission_sets) {
379 if (name == nps.Name) {
380 named_permission_sets.Remove (nps);
384 string msg = String.Format (Locale.GetText ("Name '{0}' cannot be found."), name);
385 throw new ArgumentException (msg, "name");
390 if (fullNames != null)
393 if (_type != PolicyLevelType.AppDomain) {
394 full_trust_assemblies.Clear ();
395 named_permission_sets.Clear ();
397 // because the policy doesn't exist LoadFromFile will try to
398 // 1. use the .default file if existing (like Fx 2.0 does); or
399 // 2. use the hard-coded default values
400 // and recreate a policy file
401 if ((_location != null) && (File.Exists (_location))) {
403 File.Delete (_location);
407 LoadFromFile (_location);
409 CreateDefaultFullTrustAssemblies ();
410 CreateDefaultNamedPermissionSets ();
414 public PolicyStatement Resolve (Evidence evidence)
416 if (evidence == null)
417 throw new ArgumentNullException ("evidence");
419 PolicyStatement ps = root_code_group.Resolve (evidence);
420 return ((ps != null) ? ps : PolicyStatement.Empty ());
423 public CodeGroup ResolveMatchingCodeGroups (Evidence evidence)
425 if (evidence == null)
426 throw new ArgumentNullException ("evidence");
428 CodeGroup cg = root_code_group.ResolveMatchingCodeGroups (evidence);
429 return ((cg != null) ? cg : null);
432 public SecurityElement ToXml ()
434 Hashtable fullNames = new Hashtable ();
435 // only StrongNameMembershipCondition so no need to loop
436 if (full_trust_assemblies.Count > 0) {
437 if (!fullNames.Contains ("StrongNameMembershipCondition")) {
438 fullNames.Add ("StrongNameMembershipCondition", typeof (StrongNameMembershipCondition).FullName);
442 SecurityElement namedPSs = new SecurityElement ("NamedPermissionSets");
443 foreach (NamedPermissionSet nps in named_permission_sets) {
444 SecurityElement se = nps.ToXml ();
445 object objectClass = se.Attributes ["class"];
446 if (!fullNames.Contains (objectClass)) {
447 fullNames.Add (objectClass, nps.GetType ().FullName);
449 namedPSs.AddChild (se);
452 SecurityElement fta = new SecurityElement ("FullTrustAssemblies");
453 foreach (StrongNameMembershipCondition snmc in full_trust_assemblies) {
454 fta.AddChild (snmc.ToXml (this));
457 SecurityElement security_classes = new SecurityElement ("SecurityClasses");
458 if (fullNames.Count > 0) {
459 foreach (DictionaryEntry de in fullNames) {
460 SecurityElement sc = new SecurityElement ("SecurityClass");
461 sc.AddAttribute ("Name", (string)de.Key);
462 sc.AddAttribute ("Description", (string)de.Value);
463 security_classes.AddChild (sc);
467 SecurityElement element = new SecurityElement (typeof (System.Security.Policy.PolicyLevel).Name);
468 element.AddAttribute ("version", "1");
469 element.AddChild (security_classes);
470 element.AddChild (namedPSs);
471 if (root_code_group != null) {
472 element.AddChild (root_code_group.ToXml (this));
474 element.AddChild (fta);
481 // NOTE: Callers are expected to check for ControlPolicy
482 internal void Save ()
484 if (_type == PolicyLevelType.AppDomain) {
485 throw new PolicyException (Locale.GetText (
486 "Can't save AppDomain PolicyLevel"));
489 if (_location != null) {
491 if (File.Exists (_location)) {
492 File.Copy (_location, _location + ".backup", true);
498 using (StreamWriter sw = new StreamWriter (_location)) {
499 sw.Write (ToXml ().ToString ());
506 // Hardcode defaults in case
507 // (a) the specified policy file doesn't exists; and
508 // (b) no corresponding default policy file exists
509 internal void CreateDefaultLevel (PolicyLevelType type)
511 PolicyStatement psu = new PolicyStatement (DefaultPolicies.FullTrust);
514 case PolicyLevelType.Machine:
515 // by default all stuff is in the machine policy...
516 PolicyStatement psn = new PolicyStatement (DefaultPolicies.Nothing);
517 root_code_group = new UnionCodeGroup (new AllMembershipCondition (), psn);
518 root_code_group.Name = "All_Code";
520 UnionCodeGroup myComputerZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.MyComputer), psu);
521 myComputerZone.Name = "My_Computer_Zone";
522 // TODO: strongname code group for ECMA and MS keys
523 root_code_group.AddChild (myComputerZone);
525 UnionCodeGroup localIntranetZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.Intranet),
526 new PolicyStatement (DefaultPolicies.LocalIntranet));
527 localIntranetZone.Name = "LocalIntranet_Zone";
528 // TODO: same site / same directory
529 root_code_group.AddChild (localIntranetZone);
531 PolicyStatement psi = new PolicyStatement (DefaultPolicies.Internet);
532 UnionCodeGroup internetZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.Internet), psi);
533 internetZone.Name = "Internet_Zone";
535 root_code_group.AddChild (internetZone);
537 UnionCodeGroup restrictedZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.Untrusted), psn);
538 restrictedZone.Name = "Restricted_Zone";
539 root_code_group.AddChild (restrictedZone);
541 UnionCodeGroup trustedZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.Trusted), psi);
542 trustedZone.Name = "Trusted_Zone";
544 root_code_group.AddChild (trustedZone);
546 case PolicyLevelType.User:
547 case PolicyLevelType.Enterprise:
548 case PolicyLevelType.AppDomain:
549 // while the other policies don't restrict anything
550 root_code_group = new UnionCodeGroup (new AllMembershipCondition (), psu);
551 root_code_group.Name = "All_Code";
556 internal void CreateDefaultFullTrustAssemblies ()
558 // (default) assemblies that are fully trusted during policy resolution
559 full_trust_assemblies.Clear ();
560 full_trust_assemblies.Add (DefaultPolicies.FullTrustMembership ("mscorlib", DefaultPolicies.Key.Ecma));
561 full_trust_assemblies.Add (DefaultPolicies.FullTrustMembership ("System", DefaultPolicies.Key.Ecma));
562 full_trust_assemblies.Add (DefaultPolicies.FullTrustMembership ("System.Data", DefaultPolicies.Key.Ecma));
563 full_trust_assemblies.Add (DefaultPolicies.FullTrustMembership ("System.DirectoryServices", DefaultPolicies.Key.MsFinal));
564 full_trust_assemblies.Add (DefaultPolicies.FullTrustMembership ("System.Drawing", DefaultPolicies.Key.MsFinal));
565 full_trust_assemblies.Add (DefaultPolicies.FullTrustMembership ("System.Messaging", DefaultPolicies.Key.MsFinal));
566 full_trust_assemblies.Add (DefaultPolicies.FullTrustMembership ("System.ServiceProcess", DefaultPolicies.Key.MsFinal));
569 internal void CreateDefaultNamedPermissionSets ()
571 named_permission_sets.Clear ();
573 SecurityManager.ResolvingPolicyLevel = this;
574 named_permission_sets.Add (DefaultPolicies.LocalIntranet);
575 named_permission_sets.Add (DefaultPolicies.Internet);
576 named_permission_sets.Add (DefaultPolicies.SkipVerification);
577 named_permission_sets.Add (DefaultPolicies.Execution);
578 named_permission_sets.Add (DefaultPolicies.Nothing);
579 named_permission_sets.Add (DefaultPolicies.Everything);
580 named_permission_sets.Add (DefaultPolicies.FullTrust);
583 SecurityManager.ResolvingPolicyLevel = null;
587 internal string ResolveClassName (string className)
589 if (fullNames != null) {
590 object name = fullNames [className];
592 return (string) name;
597 internal bool IsFullTrustAssembly (Assembly a)
599 AssemblyName an = a.UnprotectedGetName ();
600 StrongNamePublicKeyBlob snpkb = new StrongNamePublicKeyBlob (an.GetPublicKey ());
601 StrongNameMembershipCondition snMC = new StrongNameMembershipCondition (snpkb, an.Name, an.Version);
602 foreach (StrongNameMembershipCondition sn in full_trust_assemblies) {
603 if (sn.Equals (snMC)) {