R – The correct way to call unmanaged code from partially trusted code

cominteropnetSecuritysharepoint

What is the correct way to call unmanaged code such as a COM API through .Net interop from a code that is being executed in a partially trusted environment?

While developing an ASP.Net WebPart for Microsoft SharePoint I had to communicate with another system through its COM API. I solved this issue temporarily by changing SharePoint's permissions to full. Later I refined this by implementing custom security on top of the minimal settings which gives SharePoint UnmanagedCode permission but this isn't that big of an improvement as unmanaged code can skip the rest of the CAS.

From what I have gathered I probably need a fully trusted assembly which allows partially trusted callers and acts as a layer between the managed and unmanaged domains. Also I'd imagine there is a need for some extra settings which allow the partially trusted code call fully trusted code without the fully trusted code suffering from the permissions of the partially trusted code.

So what is the correct way and how to implement it in practice?

Best Answer

Yes, you need a fully trusted assembly which allows partially trusted callers and acts as a layer between the managed and unmanaged domains.

If you write code that must interact with partially trusted code or operate from a partially trusted context, you should consider the following factors:

  • Libraries must be signed with a strong name in order to be shared by multiple applications. Strong names allow your code to be placed in the global assembly cache and allow consumers to verify that a particular piece of mobile code actually originates from you.
  • By default, strong-named shared libraries perform an implicit LinkDemand for full trust automatically, without the library writer having to do anything.
  • If a caller does not have full trust but still tries to call such a library, the runtime throws a SecurityException and the caller is not allowed to link to the library.
  • In order to disable the automatic LinkDemand and prevent the exception from being thrown, you can place the AllowPartiallyTrustedCallersAttribute attribute on the assembly scope of a shared library. This attribute allows your libraries to be called from partially trusted managed code.
  • Partially trusted code that is granted access to a library with this attribute is still subject to further restrictions defined by local machine policy.
  • There is no programmatic way for partially trusted code to call a library that does not have the AllowPartiallyTrustedCallersAttribute attribute. If an application does not receive full trust by default, an administrator must choose to modify security policy and grant the application full trust before it can call such a library.

Source: MSDN: Using Libraries from Partially Trusted Code