Keep the Assertion Window Small

Keep the Assertion Window Small

Once you've completed the task that required the special asserted permission, you should call CodeAccessPermission.RevertAssert to disable the Assert. This is an example of least privilege; you used the asserted permission only for the duration required, and no more.

The following sample C# code outlines how asserting, demanding, and reverting can be combined to send e-mail alerts. The caller must have permission to send e-mail, and if the user does, she can send e-mail over the SMTP socket, even if she doesn't have permission to open any socket:

using System; using System.Net; using System.Security; using System.Security.Permissions; //Code fragment only; no class or namespace included. static void SendAlert(string alert) { //Demand caller can send e-mail. new EmailAlertPermission( EmailAlertPermission.Send).Demand(); //Code will open a specific port on a specific SMTP server. NetworkAccess na = NetworkAccess.Connect; TransportType type = TransportType.Tcp; string host = "mail.northwindtraders.com"; int port = 25; new SocketPermission(na, type, host, port).Assert(); try { SendAlertTo(host, port, alert); } finally { //Always revert, even on failure CodeAccessPermission.RevertAssert(); } }

When an Assert, Deny, and PermitOnly are all on the same frame, the Deny is honored first, then Assert, and then PermitOnly.

Imagine method A() calls B(), which in turn calls C(), and A() denies the ReflectionPermission permission. C() could still assert ReflectionPermission, assuming the assembly that contains it has the permission granted to it. Why? Because when the runtime hits the assertion, it stops performing a stack-walk and never recognizes the denied permission in A(). The following code sample outlines this without using multiple assemblies:

private string filename = @"c:\files\fred.txt"; private void A() { new FileIOPermission( FileIOPermissionAccess.AllAccess,filename).Deny(); B(); } private void B() { C(); } private void C() { try { new FileIOPermission( FileIOPermissionAccess.AllAccess,filename).Assert(); try { StreamWriter sw = new StreamWriter(filename); sw.Write("Hi!"); sw.Close(); } catch (IOException e) { Console.Write(e.ToString()); } } finally { CodeAccessPermission.RevertAssert(); } }

If you remove the Assert from C(), the code raises a SecurityException when the StreamWriter class is instantiated because the code is denied the permission.



Writing Secure Code
Writing Secure Code, Second Edition
ISBN: 0735617228
EAN: 2147483647
Year: 2001
Pages: 286

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net