Overzealous Use of Assert

Overzealous Use of Assert

The .NET CLR offers a method, named Assert, that allows your code, and downstream callers, to perform actions that your code has permission to do but its callers might not have permission to do. In essence, Assert means, I know what I'm doing; trust me. What follows in the code is some benign task that would normally require the caller to have permission to perform.

IMPORTANT
Do not confuse the .NET common language runtime security CodeAccessPermission.Assert method with the classic C and C++ assert function or the .NET Framework Debug.Assert method. The latter evaluate an expression and display a diagnostic message if the expression is false.

For example, your application might read a configuration or lookup file, but code calling your code might not have permission to perform any file I/O. If you know that your code's use of this file is benign, you can assert that you'll use the file safely.

That said, there are instances when asserting is safe, and others when it isn't. Assert is usually used in scenarios in which a highly trusted library is used by lower trusted code and stopping the stack-walk is required. For example, imagine you implement a class to access files over a universal serial bus (USB) interface and that the class is named UsbFileStream and is derived from FileStream. The new code accesses files by calling USB Win32 APIs, but it does not want to require all its callers to have permission to call unmanaged code, only FileIOPermission. Therefore, the UsbFileStream code asserts UnmanagedCode (to use the Win32 API) and demands FileIOPermission to verify that its callers are allowed to do the file I/O.

However, any code that takes a filename from an untrusted source, such as a user, and then opens it for truncate is not operating safely. What if the user sends a request like ../../boot.ini to your program? Will the code delete the boot.ini file? Potentially yes, especially if the access control list (ACL) on this file is weak, the user account under which the application executes is an administrator, or the file exists on a FAT partition.

When performing security code reviews, look for all security asserts and double-check that the intentions are indeed benign, especially if you have a lone Assert with no Demand or an Assert and a Demand for a weak permission. For example, you assert unmanaged code and demand permission to access an environment variable.

NOTE
To assert a permission requires that your code has the permission in the first place.

IMPORTANT
Be especially careful if your code asserts permission to call unmanaged code by asserting SecurityPermissionFlag.UnmanagedCode; an error in your code might lead to unmanaged code being called inadvertently.



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