How to deny reflection using ReflectionPermission

2019-02-05 20:21发布

问题:

I am trying to add addons in my application, but I don't want the addon to use reflection at all, the addon code can be sandbox using Application Domain.

I have found a AppDomain example at MSDN, but does not have any references for ReflectionPermision, and also the Deny security attribute is depreciated, lots of attributes are depreciated, how do I stop reflection then?

回答1:

To use AppDomain.CreateDomain to create a sandboxed appdomain, you should pass in a PermissionSet that contains only the permissions you want to grant to the sandboxed assemblies. If you don't want to grant ReflectionPermission, you simply shouldn't add it to the permission set.

That said, ReflectionPermission is far from the only "dangerous" permission that should usually be denied to general-source add-ins. If you want to be very strict, you may want to consider granting only SecurityPermission\Execution. e.g.:

PermissionSet permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

If you want to include additional "safe" permissions, you can simply add them to the permission set using additional AddPermission calls. If you want to include all the permissions that were considered safe enough to be granted to internet-sourced code under to deprcated CAS policy system, you can extract these by passing internet-zone evidence to the SecurityManager.GetStandardSandbox static method. e.g.:

Evidence evidence = new Evidence();
evidence.AddHostEvidence(new Zone(SecurityZone.Internet));

PermissionSet permissionSet = SecurityManager.GetStandardSandbox(evidence);

N.B.: Both of these approaches are described in the MSDN article to which you refered in your question.



回答2:

According to the documentation, ReflectionPermission is something you grant to give code access to private and protected members. By default it is not granted and code only has access to public members. If you are trying to hide the public members, you will need to create a new interface that does not expose them.