Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sandbox an assembly or C# source file

Tags:

c#

We want to provide some programmability features to our clients, so we allow them to write their own code, but they must not have access to system features, like

File.Delete( "test.txt" );

We partially accomplished this by not allowing global or local using statements.

But the users still would be able to access all .NET features by writing fully qualified names, like:

System.IO.File.Delete( "test.txt" );

Do you know of ways to restrict certain source files, or complete assemblies, from accessing system functions?

like image 742
cskwg Avatar asked Feb 03 '26 11:02

cskwg


1 Answers

If you are using .net framework (not net core or net5+) you could run the user's code in a separate AppDomain with restricted permissions.

Just a few hints (there are a lot of other permissions you can set):

var setup = new AppDomainSetup();

var perm = new PermissionSet(PermissionState.None);

perm.AddPermission(
       new SecurityPermission(SecurityPermissionFlag.Execution));

perm.AddPermission(
       new FileIOPermission(FileIOPermissionAccess.Read, "PathToReadOnlyFolder"));

var userCodeDomain = AppDomain.CreateDomain("UserCodeDomain", null, setup, perm);
like image 94
Alberto Avatar answered Feb 04 '26 23:02

Alberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!