Saturday, December 11, 2010

UnSafe Code

By default, Microsoft’s C# compiler produces safe code. Safe code is code that is verifiably safe. However, Microsoft’s C# compiler allows developers to write unsafe code. Unsafe code is allowed to work directly with memory addresses and can manipulate bytes at these addresses. This is a very powerful feature and is typically useful when interoperating with unmanaged code or when you want to improve the performance of a time-critical algorithm.

However, using unsafe code introduces a significant risk: unsafe code can corrupt data structures and exploit or even open up security vulnerabilities. For this reason, the C# compiler requires that all methods that contain unsafe code be marked with the unsafe keyword. In addition, the C# compiler requires you to compile the source code by using the /unsafe compiler switch.

When the JIT compiler attempts to compile an unsafe method, it checks to see if the assembly containing the method has been granted the System.Security.Permissions.Security Permission with the System.Security.Permissions.SecurityPermissionFlag’s SkipVerification flag set. If this flag is set, the JIT compiler will compile the unsafe code and allow it to execute. The CLR is trusting this code and is hoping the direct address and byte manipulations do not cause any harm. If the flag is not set, the JIT compiler throws either a System.InvalidProgramException or a System.Security.VerificationException, preventing the method from executing. In fact, the whole application will probably terminate at this point, but at least no harm can be done.


  1. What happens when third party dot net dlls are used? In what way can we check the dlls are calling unsafe methods or not? Do we have tools that inspect the third party dlls for checking any security vulnerabilities?

  2. Good questions Srini, as usual. To take control, Security.Permissions namespace helps as indicated in the last para. In terms of tools, there are few tools like Axivion, Lanquard, DLLHijackAuditor in the market. But, I would recommend to learn from Microsoft's security tech blog '' for latest frequent updates.

  3. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in dot net programming your post help me a lot.Thanks for your informative article.Dot Net training in chennai | dot net training and placement | Dot Net training in velachery