2 using System.Collections;
4 using System.Security.Permissions;
5 using System.Security.Policy;
9 // note: you cannot load a file directly into a PermissionSet
10 // but we can hack around this by using PermissionSetAttribute ;-)
11 static PermissionSet LoadFromFile (string filename)
13 // the SecurityAction is meaningless here
14 PermissionSetAttribute psa = new PermissionSetAttribute (SecurityAction.Demand);
16 return psa.CreatePermissionSet ();
19 // source: http://blogs.msdn.com/shawnfa/archive/2004/10/22/246549.aspx
20 static PermissionSet GetNamedPermissionSet (string name)
22 bool foundName = false;
23 PermissionSet pset = new PermissionSet (PermissionState.Unrestricted);
25 IEnumerator e = SecurityManager.PolicyHierarchy ();
26 while (e.MoveNext ()) {
27 PolicyLevel pl = e.Current as PolicyLevel;
29 PermissionSet levelpset = pl.GetNamedPermissionSet (name);
30 if ((levelpset != null) && (pset != null)) {
32 pset = pset.Intersect (levelpset);
36 if (pset == null || !foundName)
37 return new PermissionSet (PermissionState.None);
39 return new NamedPermissionSet (name, pset);
42 // source: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
43 static AppDomain CreateRestrictedDomain (string filename)
45 PermissionSet emptySet = new PermissionSet (PermissionState.None);
46 PolicyStatement emptyPolicy = new PolicyStatement (emptySet);
47 UnionCodeGroup root = new UnionCodeGroup (new AllMembershipCondition (), emptyPolicy);
49 PermissionSet userSet = null;
50 if (filename [0] == '@')
51 userSet = GetNamedPermissionSet (filename.Substring (1));
53 userSet = LoadFromFile (filename);
55 PolicyStatement userPolicy = new PolicyStatement (userSet);
56 root.AddChild (new UnionCodeGroup (new AllMembershipCondition (), userPolicy));
58 PolicyLevel pl = PolicyLevel.CreateAppDomainLevel ();
59 pl.RootCodeGroup = root;
61 AppDomain ad = AppDomain.CreateDomain ("Restricted");
62 ad.SetAppDomainPolicy (pl);
66 static int Main (string[] args)
68 switch (args.Length) {
70 Console.WriteLine ("Create a restricted sandbox to execute an assembly.");
71 Console.WriteLine ("Usage: mono sandbox.exe [@namedpermissionset | permissionset.xml] assembly.exe [parameters ...]");
74 Console.WriteLine ("Using default (current) appdomain to load '{0}'...", args [0]);
75 return AppDomain.CurrentDomain.ExecuteAssembly (args [0]);
77 AppDomain ad = CreateRestrictedDomain (args [0]);
78 return ad.ExecuteAssembly (args [1]);
80 ad = CreateRestrictedDomain (args [0]);
81 string[] newargs = new string [args.Length - 2];
82 for (int i=2; i < args.Length; i++)
83 newargs [i-2] = args [i];
84 return ad.ExecuteAssembly (args [1], null, newargs);