Search code examples
.netsecurityclrcode-access-security

Code Access Security is a joke?


I have just read about this article about Code Access Security. It has such an example in it:

using System.Security.Permissions;
public class MyFileAccessor 
{
  public MyFileAccessor(String path, bool readOnly)
  {
    path = MakeFullPath(path); // helper fcn
    FileIOPermissionAccess desiredAccess = readOnly
      ? FileIOPermissionAccess.Read
      : FileIOPermissionAccess.AllAccess;
    FileIOPermission p = new FileIOPermission(desiredAccess, path);
    p.Demand();
    // 
    ••• 
    open the file
   }
   // •••
}

What if I didn't use the FileIOPermissionAccess type and never includ code like p.Demand() in my code at all? In other words, if I want to do something bad, why should I bother to ask permission for that? Isn't it kind of a joke? OR did I take it wrong?


Solution

  • Well, yes, the example is a bit of a joke, you'd never write something like this yourself. What's missing is the really important part, the code that // opens the file. A realistic version of it would, say, pinvoke CreateFile().

    The point being that Windows doesn't know anything about CAS. So if you provide a utility function like this and you want to enforce the CAS rules then you have to verify that your calling code has the required permission. Of course, this kind of code really only belongs in the .NET framework. Have a look-see at FileStream.Init() and note FileIOPermission being demanded there before the CreateFile call.