views:

82

answers:

1

The following code exists in LogEntry.cs in the Enterprise Library's Logging Application Block:

private bool UnmanagedCodePermissionAvailable
{
  get
  {
    if (!unmanagedCodePermissionAvailableInitialized)
    {
      // check whether the unmanaged code permission is available to avoid three potential stack walks
      bool internalUnmanagedCodePermissionAvailable = false;
      SecurityPermission unmanagedCodePermission = 
                  new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
      // avoid a stack walk by checking for the permission on the current assembly. this is safe because there are no
      // stack walk modifiers before the call.
      if (SecurityManager.IsGranted(unmanagedCodePermission))
      {
        try
        {
          unmanagedCodePermission.Demand();
          internalUnmanagedCodePermissionAvailable = true;
        }
        catch (SecurityException)
        { }
      }

      this.UnmanagedCodePermissionAvailable = 
          internalUnmanagedCodePermissionAvailable;
    }

    return this.unmanagedCodePermissionAvailable;
  }
  set
  {
    this.unmanagedCodePermissionAvailable = value;
    unmanagedCodePermissionAvailableInitialized = true;
  }
}

The function is called before any of several P/Invoke calls are made to retrieve various information to help fill in the LogEntry structure. If "UnmanagedCodePermission" is not available, then the corresponding LogEntry property is set to a string indicating such ("XXX is not available").

For example, LogEntry wants to get the Win32 thread id and it uses the Win32 function, GetCurrentThreadId, called by P/Invoke to get it. Before calling GetCurrentThreadId, it checks to see if "unamanged code permission" is available. If so, it makes the call, if not, it does not. Something like this:

private void InitializeWin32ThreadId()
{
  if (this.UnmanagedCodePermissionAvailable)
  {
    try
    {
      this.Win32ThreadId = LogEntryContext.GetCurrentThreadId();
    }
    catch (Exception e)
    {
      this.Win32ThreadId = string.Format(
                                  CultureInfo.CurrentCulture,
                                  Properties.Resources.IntrinsicPropertyError,
                                  e.Message);
    }
  }
  else
  {
    this.Win32ThreadId = string.Format(CultureInfo.CurrentCulture,
                Properties.Resources.IntrinsicPropertyError,
                Properties.Resources.
                LogEntryIntrinsicPropertyNoUnmanagedCodePermissionError);
  }
}

From what I understand, which, admittedly, is not much, making calls to unmanaged code (e.g. P/Invoke) is not always possible due to security/permissions/trust. Having this check to see if unmanaged code calls are possible, makes it possible to protect all unmanaged calls in a uniform manner.

When I compile this code, I get a warning on this line:

          if (SecurityManager.IsGranted(unmanagedCodePermission))

Here is the warning:

System.Security.SecurityManager.IsGranted(System.Security.IPermission)' is obsolete: 'IsGranted is obsolete and will be removed in a future release of the .NET Framework. Please use the PermissionSet property of either AppDomain or Assembly instead.

(Note that I am building this on .Net 4.0 using VS2010).

So, it looks IsGranted is obsolete. I looked at the PermissionSet property for AppDomain and Assembly, and it wasn't obvious exactly how to make the same check.

In the case of LogEntry, it looks like this information is not critical, so it is not considered a critical failure if unmanaged permission is not available. Consider the following questions from the same point of view. That is, if unmanaged code permission is not available, it is not a huge deal, I can live without the information.

Finally, a couple of questions:

  1. Is it a good idea to try to protect calls to unmanaged code (e.g. P/Invoke)? Sometimes, always, never?

  2. If it is a good idea to protect these calls, is this a reasonable pattern for doing so? Is there a better way?

  3. What would be the correct (i.e. not obsolete) way to make the equivalent check in .Net 4.0?

+1  A: 

Before .NET 4, Code Access Security (CAS) was the security model used by the .NET Fx. Idea was to identify what code can do based on evidence and don't allow to do it any other things (SandBoxing). For example, code present on your local computer by default gets full trust (essentially it can do anything) while code coming from internet will have restricted permissions (partial trust) scenario.

IMO, if you are writing code that unlikely to run in partially trusted environment then you may not concern much about it. However for partially trusted assemblies,

  1. If they can tell their host (for example IE), what permissions it needs then host can decides whether to grant those based on security policy etc. Or host may prompt user and allow him to override. Or admin would know the permission set by inspecting assembly and he may decide to update policy to allow it.
  2. In case, host does not grant needed permission to the code then code can check it and handle it gracefully instead of generating into security exception.

So above code illustrates ways to achieve this prior to .NET 4. In .NET 4, there is new security model that is more simpler to use. See this & this article for more information.

VinayC