Click here to Skip to main content
15,881,588 members
Articles / .NET

Who Knows of the .NET Secure Strings?

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
25 Jan 2010CPOL4 min read 18.2K   6   6
While SecureString is certainly not a new kid on the block, it is often overlooked by .NET programmers that are programming applications that deal with sensitive data (think PCI, KeyManagement, Passwords, Credit cards, etc.)...

[Warning this is not new stuff - but shouldn't be overlooked if you need to secure sensitive data in your application.]

Isn't “Secure String” an oxymoron for .NET? So if we are thinking about securing some sensitive data in say C or C++, it's relatively simple- load it into a char array memory and encrypt it, wiping the memory out after the information has been loaded.

Now try that with .NET! From the Microsoft site:

A String is called immutable because its value cannot be modified once it has been created.

So how can you destroy one? Set it to empty? Well simply put, you can't :-). Once your string is no longer referenced, or worse yet your object containing the string, it's time for the Garbage Collector to come and do its work. The problem is if your object has been around long enough to get into Generation 1 or 2, then it is going to take a bit longer.

Hmmm, so in translation, if you keep a password, Credit Card, encryption key or some other sensitive text in memory as a string, you can't destroy it (think memset for us oldies!). Only the GC can free the memory for you, and you are dependent on HOW it frees that memory. I personally don't know for a fact if it memsets it to blank, or just dereferences the pointer. However, I would be willing to bet it is the option that requires the least amount of work and that doesn't bode well for controlling the exposure of our sensitive data.

Plainly that proverbially sucks!

Enter the “SecureString” class, from the Microsoft site, it says:

“Represents text that should be kept confidential. The text is encrypted for privacy when being used, and deleted from computer memory when no longer needed.”

Wow, doesn't that just sound like the ticket we need! Secure, Encryption, delete from memory – how fantastic! Uh oh, keep reading the remarks:

“Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method.

Use appropriate members of the System.Runtime.InteropServices..::.Marshal class, such as the SecureStringToBSTR method, to manipulate the value of a SecureString object.”

BSTR – oh I feel the COM headache coming back!

Actually, it's really not that bad, but it's definitely not a straight swap for a System.String. See some example code below:

C#
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security;

namespace CSharpHacker.Utilities
{
   /// <summary>
   /// Demo helper class for <see cref="SecureString"/>
   /// </summary>
   public class SensitiveDataHelper
   {
      private SecureString sensitiveData;

      /// <summary>
      /// Gets or sets the sensitive data class from helper
      /// </summary>
      /// <value>The sensitive data container.</value>
      public SecureString SensitiveData
      {
         get { return sensitiveData; }
         set { sensitiveData = value; }
      }

      /// <summary>
      /// UNSECURE: Converts the secured sensitive data into an unsecured string.
      /// </summary>
      /// <remarks>
      /// This is a dangerous function that converts secured information into
      /// unsecured data.
      /// </remarks>
      /// <returns>String representing the secured data</returns>
      public string SensitiveDataToString()
      {
         IntPtr ptr = Marshal.SecureStringToGlobalAllocUnicode(this.sensitiveData);
         try
         {
             // Unsecure managed string
             return Marshal.PtrToStringUni(ptr);
         }
         finally
         {
             Marshal.ZeroFreeGlobalAllocUnicode(ptr);
         }
      }

      /// <summary>
      /// UNSECURE: Base64s encodes a SHA512 has of the sensitive data
      /// </summary>
      /// <returns>SHA512 hash value</returns>
      public string Base64SensitiveDataHash()
      {
         IntPtr bstr = Marshal.SecureStringToBSTR(sensitiveData);
         try
         {
            // Pretend simple hash function that returns a string - 
            // this is fake just for readability!!
            string output = Marshal.PtrToStringBSTR(bstr);

            Marshal.FreeBSTR(bstr);

            SHA512 sha = new SHA512Managed();
            byte[] result = sha.ComputeHash(Encoding.UTF8.GetBytes(output));
            return Convert.ToBase64String(result);
         }
         finally
         {
            Marshal.ZeroFreeBSTR(bstr);
         }
      }

      /// <summary>
      /// Loads the sensitive data into a <see cref="SecureString"/>
      /// </summary>
      /// <param name="sensitiveInformation">The sensitive information to protect.</param>
      public void LoadSensitiveData(char[] sensitiveInformation)
      {
         try
         {
            using (SecureString securePassword = new SecureString())
            {
               foreach (char c in sensitiveInformation)
               {
                  securePassword.AppendChar(c);
               }
               securePassword.MakeReadOnly();
               this.sensitiveData = securePassword.Copy();
            }
         }
         finally
         {
            // discard the char array
            Array.Clear(sensitiveInformation, 0, sensitiveInformation.Length);
         }
      }

      /// <summary>
      /// Loads the sensitive data into a <see cref="SecureString"/>
      /// </summary>
      /// <param name="sensitiveInformation">The sensitive information to protect.</param>
      public void LoadSensitiveData(string sensitiveInformation)
      {
         char[] sensitive = new char[sensitiveInformation.Length];
         sensitiveInformation.CopyTo(0, sensitive, 0, sensitive.Length);

         LoadSensitiveData(sensitive);
      }

      /// <summary>
      /// Loads the sensitive data into a <see cref="SecureString"/>
      /// </summary>
      /// <param name="sensitiveInformation">The sensitive information to protect.</param>
      public void LoadSensitiveData(StringBuilder sensitiveInformation)
      {
         char[] sensitive = new char[sensitiveInformation.Length];
         sensitiveInformation.CopyTo(0, sensitive, 0, sensitive.Length);

         LoadSensitiveData(sensitive);
      }

      /// <summary>
      /// Creates the secure string from string.
      /// </summary>
      /// <param name="unprotectedSensitiveInformation">
      /// The unprotected sensitive information.</param>
      /// <returns></returns>
      public static SecureString CreateSecureStringFromString
			(string unprotectedSensitiveInformation)
      {
         char[] unprotectedSensitive = unprotectedSensitiveInformation.ToCharArray();
         SecureString secureInformation = new SecureString();
         try
         {
            foreach (char c in unprotectedSensitive)
            {
               secureInformation.AppendChar(c);
            }
            secureInformation.MakeReadOnly();
            return secureInformation;
         }
         finally
         {
            // discard the char array
            Array.Clear(unprotectedSensitive, 0, unprotectedSensitive.Length);
         }
      }
   }
}

A word of caution to the above code:

  • SensitiveDataToString – is considered insecure as it returns a string of the encrypted data. The same data we are trying to encrypt! However, it is a commonly requested function, and so there is the implementation.
  • Base64SensitiveDataHash – is considered insecure as it currently uses a temporary string (:-( ), at this time, I don't have a way to convert a BSTR into an array without going through a string first. One way would be to process it prior to being made ReadOnly, or alternatively someone can write a comment on how to convert a C# BSTR into a byte array!

So even with all those disclaimers, running a program that takes input will still a ‘leak information’ for the System.String. Specifically, the tricky area is how do you get them into your program in the first place? Read them from a database, WinForm user input, or a web page? Kinda tricky :-) ! If you search the web, there are implementations of  secure login controls that build it up character by character, but certainly something to think about.

So how Secure is “SecureString”? The answer is “it depends”, but reasonably secure and a heck of a lot better than System.String. A while ago, there was a big storm about tools that can connect to the process and decrypt your SecureStrings. The best rebuttal to this I've seen can be read about in [SecureString Redux]. I definitely recommend reading this.

Now I have to say I've been meaning to write this for some time now! Hopefully this helped raise awareness of the string leakage risks in the .NET language and ways to help minimize the string information leak scenario.

Potential enhancements to the helper class would be:

  • Make the Hashing really secure, and allow a “HashAlgorithm” to be passed in
  • Allow external encryption
  • Allow secure serialization of data (via the encryption)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I'm Gareth and am a guy who loves software! My day job is working for a retail company and am involved in a large scale C# project that process large amounts of data into up stream data repositories.

My work rule of thumb is that everyone spends much more time working than not, so you better enjoy what you do!

Needless to say - I'm having a blast.

Have fun,

Gareth

Comments and Discussions

 
QuestionMight stringbuilders be helpful? Pin
supercat925-Jan-10 7:32
supercat925-Jan-10 7:32 
AnswerRe: Might stringbuilders be helpful? Pin
GarethI25-Jan-10 8:36
GarethI25-Jan-10 8:36 
GeneralRe: Might stringbuilders be helpful? Pin
supercat925-Jan-10 11:45
supercat925-Jan-10 11:45 
AnswerRe: Might stringbuilders be helpful? Pin
Druuler25-Jan-10 13:46
Druuler25-Jan-10 13:46 
GeneralRe: Might stringbuilders be helpful? Pin
supercat926-Jan-10 5:56
supercat926-Jan-10 5:56 
JokeRe: Might stringbuilders be helpful? Pin
GarethI26-Jan-10 7:29
GarethI26-Jan-10 7:29 
Smile | :) I was only going to say the "unsafe" keyword is fairly descriptive! Its not something you really want to mess about with!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.