Saturday, August 25, 2007

Secure Strings in .Net

[System].String objects contains an array of characters that reside somewhere in memory. We usually store our confidential entities (information that is meant to be secure) in these String objects. This information can range from your password to you salary code. If some un-managed/ unsafe code is allowed to run, that code can get into our process's address space, find out the required String object and use it in any way as it like.

As we all know, Strings objects are immutable i.e. once a string object is created they never change. Old versions of String object are scattered all over memory. There is no guarantee when garbage collector will run and clean up our application’s managed heap. Before GC wakes up, these string objects are within reach of some unsafe code. Unsafe here means code that is manipulating memory pointer. Even if string objects are used for short time and then are garbage collected by the run time, this doesn't mean that memory space used by string will be allocated to another object just after garbage collection (especially if string object was in older generation).

If some government office like CBI (Indian Investigating Agency) approaches you to create a secure application which will handle data about national security, “System.String” type objects will not meet stringent security requirements that application needs. Sensitive information lying in memory can be very tempting for anti social elements (this includes hackers). Due to these requirements Microsoft introduced another type of string class:

  • Class Name: SecureString
  • Name Space: System.Security

When we create an object of SecureString type, it internally allocates a block of memory that contains an array of characters. Now the surprise! this is an un-managed block of memory and this is because runtime don't want garbage collector to know about these SecureString objects. GC knows about all the objects lying in the heap. It has no information regarding object type but it knows its memory address. This class is just in its budding phase and does not provide only few features that are provided with System.String class. Data is encrypted before storing and decrypted before being read. So with good functionality it gives us some bad performance overheads.

System.Secure.SecureString class implements Dispose pattern i.e. it implements IDisposable interface. Another surprise, its Dispose method is called implicitly (i.e. automatically). You don’t need to call this method explicitly. CLR calls SecureString’s Dispose when it realizes that this string is not needed or it is out of scope. Dispose ensures that all memory contents used by object of SecureString type are zeroed out. This class is derived from CriticalFinalizerObject which ensures that finalize method of this class is called no matter what happens. CriticalFinalizerObject in itself deserves a good amount of space. But I’ll leave it for now.

There are certain limitations around usage of SecureString in .Net 2.0.

to be continued…

Thursday, August 16, 2007

Singleton - One of a Kind Objects (Part II)

How will we tame the multi threading beast?
I'm a .Net developer having CLR as my run time. I never worked on Java, but C# and JAVA are almost similar. C# is advance form of JAVA and CLR is much more refine than JVM. Things that comes later are generally more advanced than things that came earlier. I was first introduced to this multi threading problem while going throgh Head First Design Patterns book. According to the book it was damn simple to fix this problem by making access to MySingleton.GetMySingletonInstance() synchronized. Code for this is simple as Singleton class itself,

using System;
using System.Runtime.CompilerServies;
internal sealed class MySingleton
{
//static variable to hold instance reference
private static MySingleton onlyInstance;
private MySingleton();
//Global i.e. public and static point of access
//No two treads may enter the method at the same time

[MethodImpl(MethodImplOptions.Synchronized)]
public static MySingleton GetMySingletonInstance()
{
if (onlyInstance==null)
{
onlyInstance=new MySingleton();
}
return onlyInstance;
}
}


This is as simple as it can get.We just decorated our method with MethodImpl attribute. This is available in System.Runtime.CompilerServices namespace. Now, no two threads can enter our GetMySingletonInstance() method at the same time. This solves the problem but leaves us with another headache, performance. We all know that this synchronization is only needed when onlyInstance is null i.e. we haven't yet created the MySingleton object. So adding synchronization lock to our method doesn't makes sense. Its just like solving one problem and creating another.


Now What?
There is a well known technique used to solve this problem. This is called Double Check Locking Technique. It's used when you want to have lazy instantiation i.e. you want your object to be constructed when your application first requests it. This is not a well known technique because its particularly interesting or useful. It's well known because a lot is written about it and a lot of Java developers use it. This was quite heavily used in Java but lately its discovered that this technique doesn't guarantee that it would work everywhere. If you want to know why this fails then just read through http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html. Just to show you how this double checking is implemented in C# I'll add some code here,

internal sealed class MySingleton
{
private static volatile MySingleton onlyInstance= null;
protected MySingleton() {}
public static MySingleton GetMySingletonInstance()
{
if (onlyInstance == null)
{
lock (typeof(MySingleton))
{
if (onlyInstance == null)
{
onlyInstance = new MySingleton();
}
}
}
return onlyInstance; }
}
What is the best implementation?
Use Type Initializer (static constructor) to create a simple and best implementation of singleton.
internal sealed class MySingleton
{
//Type constructor will be called when any member of type is accessed
//This initialization code will be added to Type Constructor by JIT compiler
private static MySingleton onlyInstance= new MySingleton();
private MySingleton() {}
public static MySingleton OnlyInstance
{
get { return onlyInstance;}
}
}
CLR automatically calls type's class constructor when the code attempts the access a member of the class. CLR ensures that calls to a type constructor are thread safe. Double check locking is less efficient than this technique as you need to create your own lock object and write all additional locking code yourself. Double check locking is interesting only if class has lots of members and you want to have your singleton constructed only when one of the member is called.

I hope! I answered my friend Pramod's question related to minimize overhead associated with double check locking technique.

Wednesday, August 15, 2007

Singleton - One of a Kind Objects (Part I)

SINGLETON PATTERN

  • What is Singleton pattern?
    Singleton Pattern insures that only one instance of a Type is created and that Type provide a global point of access for that instance.
  • How it's implemented?
    Implementing a singleton type is quite simple (if synchronization is not an issue for you). Type should define a static member variable which will contain reference to type's instance. Make type's instance constructor as Private so that no other type can create instance of our singleton class.
    We need to add one static method that will check weather our static instance variable is null or not. If it is null then we will add code so that our static variable will refer to newly created type's instance. Lastly we will return that static variable.
    This way, there will always be one and only one instance of a type around (just forget about multi-threading for the time being).
  • How it looks when coded?

    internal sealed class MySingleton
    {
    //static variable to hold instance reference
    private static MySingleton onlyInstance;

    private MySingleton();

    //Global i.e. public and static point of access
    public static MySingleton GetMySingletonInstance()
    {
    if (onlyInstance==null)
    {
    onlyInstance=new MySingleton();
    }
    return onlyInstance;
    }
    }
  • How multi threading spoils our Singleton party?
    Multi threaded applications are quite common these days. Now suppose we have multiple threads running in our MySingleton application. I'll name two of my application threads as AngelThread and DevilThread. AngelThread and DevilThread both requires MySingleton instance, so they both try to call MySingleton.GetMySingletonInstance().
    AngelThread checks onlyInstance for null, as we haven't created any instance yet this returns true and code next to be executed by AngelThread is,"onlyInstance=new MySingleton();"
    Now, CPU realizes that AngelThread has got enough CPU time slice, let's switch to DevilThread. Remember AngelThread still haven't instantiated MySingleton yet. DevilThread also checks onlyInstance for null, and obviously true is returned and DevilThread is just about creating a brand new MySingleton object. DevilThread created the object and returns its reference. Our CPU interrupts and wakes up AngelThread so that it can continue its execution. Aha! AngelThread also creates a brand new object and returns. So we have two objects of MySingleton type. Multi threading ruined our singleton dream.

    to be continued...

Let's celebrate Independence


Tuesday, August 14, 2007

Independence Day

We all will be celebrating our country's independence day tomorrow and guess what..there is no electricity in country's capital from past 1 hour. Thank god some one invented mighty battery operated inverters. It's quite humid this time of the year and without AC it's almost impossible to live. I wish I had a laptop so that I wouldn't have to sit and do this stuff. It's painful. These are just my early blogs and I know they are of no use. I seriously want to start up something really useful.

Today during my lunch break, a friend of mine, Pramod, asked me a tricky question regarding singleton objects. I'll check that out today and will try to post something about singleton here tomorrow.

Happy Independence (without BiJli)

Console.WriteLine("Hello World");

It's been almost 7 years since I started using web and computers. Blogging is around from past 3-4 years. Now, after spending about 7 years (30660 hrs approx.) with computer, finally I got some time to start my own blog. Let's see how it shapes up. Keep your fingers crossed and hope! this goes well.

Note: If you didn't get how I came up with 30660 hrs. it's not my fault. It uses some supercomputing algorithms and it's surely not novice's cup of tea.