C# Securestring Question

C# SecureString Question

This should help you: Marshaling SecureString Passwords to String

From the article, the key points are:

  • Pin the string in memory.
  • Use managed pointers to mutate the System.String.
  • Use the strong guarantees of the ExecuteCodeWithGuaranteedCleanup method.

Convert String to SecureString

You don't. The whole reason for using the SecureString object is to avoid creating a string object (which is loaded into memory and kept there in plaintext until garbage collection). However, you can add characters to a SecureString by appending them.

var s = new SecureString();
s.AppendChar('d');
s.AppendChar('u');
s.AppendChar('m');
s.AppendChar('b');
s.AppendChar('p');
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('d');

Using SecureString

You could use Linq:

"fizzbuzz".ToCharArray().ToList().ForEach(p => secureString.AppendChar(p));

How to convert SecureString to System.String?

Use the System.Runtime.InteropServices.Marshal class:

String SecureStringToString(SecureString value) {
IntPtr valuePtr = IntPtr.Zero;
try {
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
return Marshal.PtrToStringUni(valuePtr);
} finally {
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}

If you want to avoid creating a managed string object, you can access the raw data using Marshal.ReadInt16(IntPtr, Int32):

void HandleSecureString(SecureString value) {
IntPtr valuePtr = IntPtr.Zero;
try {
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
for (int i=0; i < value.Length; i++) {
short unicodeChar = Marshal.ReadInt16(valuePtr, i*2);
// handle unicodeChar
}
} finally {
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}

Is SecureString ever practical in a C# application?

There are actually very practical uses of SecureString.

Do you know how many times I've seen such scenarios? (the answer is: many!):

  • A password appears in a log file accidentally.
  • A password is being shown at somewhere - once a GUI did show a command line of application that was being run, and the command line consisted of password. Oops.
  • Using memory profiler to profile software with your colleague. Colleague sees your password in memory. Sounds unreal? Not at all.
  • I once used RedGate software that could capture the "value" of local variables in case of exceptions, amazingly useful. Though, I can imagine that it will log "string passwords" accidentally.
  • A crash dump that includes string password.

Do you know how to avoid all these problems? SecureString. It generally makes sure you don't make silly mistakes as such. How does it avoid it? By making sure that password is encrypted in unmanaged memory and the real value can be only accessed when you are 90% sure what you're doing.

In the sense, SecureString works pretty easily:

1) Everything is encrypted

2) User calls AppendChar

3) Decrypt everything in UNMANAGED MEMORY and add the character

4) Encrypt everything again in UNMANAGED MEMORY.

What if the user has access to your computer? Would a virus be able to get access to all the SecureStrings? Yes. All you need to do is hook yourself into RtlEncryptMemory when the memory is being decrypted, you will get the location of the unencrypted memory address, and read it out. Voila! In fact, you could make a virus that will constantly scan for usage of SecureString and log all the activities with it. I am not saying it will be an easy task, but it can be done. As you can see, the "powerfulness" of SecureString is completely gone once there's a user/virus in your system.

You have a few points in your post. Sure, if you use some of the UI controls that hold a "string password" internally, using actual SecureString is not that useful. Though, still, it can protect against some stupidity I've listed above.

Also, as others have noted, WPF supports PasswordBox which uses SecureString internally through its SecurePassword property.

The bottom line is; if you have sensitive data(passwords, credit-cards, ..), use SecureString. This is what C# Framework is following. For example, NetworkCredential class stores password as SecureString. If you look at this, you can see over ~80 different usages in .NET framework of SecureString.

There are many cases when you have to convert SecureString to string, because some API expects it.

The usual problem is either:

  1. The API is GENERIC. It does not know that there's a sensitive data.
  2. The API knows that it's dealing with sensitive data and uses "string" - that's just bad design.

You raised good point: what happens when SecureString is converted to string? This can only happen because of the first point. E.g. the API does not know that it's sensitive data. I have personally not seen that happening. Getting string out of SecureString is not that simple.

It's not simple for a simple reason; it was never intended to let the user convert SecureString to string, as you stated: GC will kick in. If you see yourself doing that, you need to step back and ask yourself: Why am I even doing this, or do I really need this, why?

There's one interesting case I saw. Namely, the WinApi function LogonUser takes LPTSTR as a password, which means you need to call SecureStringToGlobalAllocUnicode. That basically gives you unencrypted password that lives in unmanaged memory. You need to get rid of that as soon as you're done:

// Marshal the SecureString to unmanaged memory.
IntPtr rawPassword = Marshal.SecureStringToGlobalAllocUnicode(password);
try
{
//...snip...
}
finally
{
// Zero-out and free the unmanaged string reference.
Marshal.ZeroFreeGlobalAllocUnicode(rawPassword);
}

You can always extend the SecureString class with an extension method, such as ToEncryptedString(__SERVER__PUBLIC_KEY), which gives you a string instance of SecureString that is encrypted using server's public key. Only server can then decrypt it. Problem solved: Garbage Collection will never see the "original" string, as you never expose it in managed memory. This is exactly what is being done in PSRemotingCryptoHelper (EncryptSecureStringCore(SecureString secureString)).

And as something very almost-related: Mono SecureString does not encrypt at all. The implementation has been commented out because ..wait for it.. "It somehow causes nunit test breakage", which brings to my last point:

SecureString is not supported in everywhere. If the platform/architecture does not support SecureString, you'll get an exception. There's a list of platforms that are supported in the documentation.

Is SecureString a write-only class?

Both ways here, a way to convert it to a securestring and from a securestring. Of course the whole point of storing it in a securestring is to prevent it from being in memory in the first place.

        #region SecureString Manipulation
/// <summary>
/// Convert a Securestring to a regular string (not considered best practice, but make sure it's not in memory if you can help it)
/// </summary>
/// <param name="securePassword">Password stored in a secure string</param>
/// <returns>regular string of securestring password</returns>
public static string ConvertToUnsecureString(this System.Security.SecureString securePassword)
{
if (securePassword == null)
throw new ArgumentNullException("securePassword");

IntPtr unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
return Marshal.PtrToStringUni(unmanagedString);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
}
}

/// <summary>
/// Pass a text password to this function to return a SecureString (doesn't store the password in memory)
/// </summary>
/// <param name="password">Text version of a password</param>
/// <returns>SecureString of a password (not readable by memory)</returns>
public static SecureString ConvertToSecureString(this string password)
{
if (password == null)
throw new ArgumentNullException("password");

var secure = new SecureString();
foreach (var c in password.ToCharArray())
secure.AppendChar(c);
return secure;
}
#endregion

How to check if SecureString contains certain text?

The best approach to check it without defeating SecureString purpose is in your Process output buffer loop, before it gets into the SecureString secured buffer. But in the best case, doing so you would create a plain memory string of the last N characters (being N the "Hello world" length) which would be a bit insecure. Less insecure than calling SecureString.ToString() of course 'cause as you already stated, it would store all the text in plain memory defeating the purpose.

How to convert a string to securestring explicitly

The simplest approach is to iterate over the source string and append one character at a time to the secure string, like so:

var secure = new SecureString();
foreach (char c in textbox1.Text)
{
secure.AppendChar(c);
}


Related Topics



Leave a reply



Submit