Security: Store strings in-memory securely.

4 במרץ 2009

תגיות: , ,
תגובה אחת

Lots of  developers are not familiar with the fact that string variables are stored in memory as a plain text and can be stolen with simple memory dump. Therefore they are revealed to anyone who has an access to a server. So all the credit card numbers, passwords, database connection strings etc. are literally exposed when no measures are taken…

A simple solution has been always there … Starting from .NET 2.0 framework there is a SecureString class in System.Security namespace. It’s functionality is similar to a string data type with several changes.

Here are several advantages of this class:

  • It’s not stored in heap memory
  • Can be made immutable edit stage was finished by calling MakeReadOnly() method
  • Stored encrypted with DPAPI
  • Can be cleared without leaving a copy (implements IDisposable)
  • Can be passed around without leaving a copies in memory (is not stores in managed heap)

SecureString does not contain any methods or properties to inspect it’s content. Therefore to get a stored value System.Runtime.Marshal.SecureStringToBSTR method must be used:

private static SecureString _SomeSecretData;

public static string SomeSecretData
{
    set
    { 
        char[] tmpData = value.ToCharArray();
        _SomeSecretData = new SecureString();
        foreach (char val in tmpData)
        {
            _SomeSecretData.AppendChar(val);
        }
        //make string immutable
        _SomeSecretData.MakeReadOnly();
    }
    get
    {
        IntPtr ptr = System.Runtime.InteropServices.
                            Marshal.SecureStringToBSTR(_SomeSecretData);
        string decryptedString = System.Runtime.InteropServices.
                                    Marshal.PtrToStringUni(ptr);

        return decryptedString;
    }
}

Summary

SecureString class provides easy to use tool for preventing … or at least making harder, to get sensitive data that is stored in-memory without any additional development overate.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

תגובה אחת