Overzealous Use of Assert

Overzealous Use of Assert

The .NET common language runtime offers a method, called 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 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 Assert method with the classic C and C++ assert function. The latter evaluates an expression and displays a diagnostic message if the expression is false.

For example, your application might read a configuration or lookup file, but the caller 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 will use the file safely.

That said, there are instances when asserting is safe, and others when it isn t. The following Microsoft Visual Basic .NET code, which reads a configuration file used solely by the application itself, is safe. Therefore, it is safe to assert the FileIOPermission permission to read the file.

Imports System Imports System.IO Imports System.Security.Permissions Public Class MyConfigFile Public Function Open() As String Try Dim f As String = c:\config\config.xml" Dim fp As New _ FileIOPermission(FileIOPermissionAccess.Read, f) fp.Assert() Dim sr As New StreamReader(f) Dim data As String = sr.ReadToEnd() sr.Close() Open = data Catch e As Exception Console.WriteLine(e.ToString()) End Try End Function End Class

However, any code that takes a filename from an untrusted source, such as a user, and then opens it for truncate is not a safe operation. 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 or if the file exists on a FAT partition.

When performing code reviews, look for all security asserts and double-check that the intentions are indeed benign.

note

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

important

Be especially careful if your code asserts permission to call untrusted code by asserting SecurityPermissionFlag.UnmanagedCode, because an error in your code might lead to untrusted code being called inadvertently.



Writing Secure Code
Writing Secure Code, Second Edition
ISBN: 0735617228
EAN: 2147483647
Year: 2005
Pages: 153

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