[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:
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security;
namespace CSharpHacker.Utilities
{
public class SensitiveDataHelper
{
private SecureString sensitiveData;
public SecureString SensitiveData
{
get { return sensitiveData; }
set { sensitiveData = value; }
}
public string SensitiveDataToString()
{
IntPtr ptr = Marshal.SecureStringToGlobalAllocUnicode(this.sensitiveData);
try
{
return Marshal.PtrToStringUni(ptr);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(ptr);
}
}
public string Base64SensitiveDataHash()
{
IntPtr bstr = Marshal.SecureStringToBSTR(sensitiveData);
try
{
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);
}
}
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
{
Array.Clear(sensitiveInformation, 0, sensitiveInformation.Length);
}
}
public void LoadSensitiveData(string sensitiveInformation)
{
char[] sensitive = new char[sensitiveInformation.Length];
sensitiveInformation.CopyTo(0, sensitive, 0, sensitive.Length);
LoadSensitiveData(sensitive);
}
public void LoadSensitiveData(StringBuilder sensitiveInformation)
{
char[] sensitive = new char[sensitiveInformation.Length];
sensitiveInformation.CopyTo(0, sensitive, 0, sensitive.Length);
LoadSensitiveData(sensitive);
}
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
{
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)
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