15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

string dir = Path.Combine<br />

(System.Runtime.InteropServices.RuntimeEnvironment<br />

.GetRuntimeDirectory(), "config");<br />

string configFile = Path.Combine (dir, "security.config");<br />

Sandboxing Another Assembly<br />

Suppose you write an application that allows consumers to install third-party plugins.<br />

Most likely you’d want to prevent plug-ins from leveraging your privileges as a<br />

trusted application, so as not to destabilize your application—or the end user’s<br />

computer. The best way to achieve this is to run each plug-in in its own sandboxed<br />

application domain.<br />

For this example, we’ll assume a plug-in is packaged as a .NET assembly called<br />

plugin.exe and that activating it is simply a matter of starting the executable. (In<br />

Chapter 24, we describe how to load a <strong>library</strong> into an application domain and interact<br />

with it in a more sophisticated way.)<br />

Here’s the complete code, for the host program:<br />

using System;<br />

using System.IO;<br />

using System.Net;<br />

using System.Reflection;<br />

using System.Security;<br />

using System.Security.Policy;<br />

using System.Security.Permissions;<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

string pluginFolder = Path.Combine (<br />

AppDomain.CurrentDomain.BaseDirectory, "plugins");<br />

string plugInPath = Path.Combine (pluginFolder, "plugin.exe");<br />

PermissionSet ps = new PermissionSet (PermissionState.None);<br />

ps.AddPermission<br />

(new SecurityPermission (SecurityPermissionFlag.Execution));<br />

ps.AddPermission<br />

(new FileIOPermission (FileIOPermissionAccess.PathDiscovery |<br />

FileIOPermissionAccess.Read, plugInPath));<br />

ps.AddPermission (new UIPermission (PermissionState.Unrestricted));<br />

AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;<br />

AppDomain sandbox = AppDomain.CreateDomain ("sbox", null, setup, ps);<br />

sandbox.ExecuteAssembly (plugInPath);<br />

AppDomain.Unload (sandbox);<br />

Sandboxing Another Assembly | 769<br />

Security

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!