Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is SecureString ever practical in a C# application?

Tags:

c#

security

People also ask

Why use SecureString?

Overall, SecureString is more secure than String because it limits the exposure of sensitive string data. However, those strings may still be exposed to any process or operation that has access to raw memory, such as a malicious process running on the host computer, a process dump, or a user-viewable swap file.

What is a SecureString Powershell?

Description. The ConvertTo-SecureString cmdlet converts encrypted standard strings into secure strings. It can also convert plain text to secure strings. It is used with ConvertFrom-SecureString and Read-Host .

Is secure string encrypted?

As others have already answered, the contents of SecureString are encrypted using DPAPI, so the keys aren't stored in your application, they're part of the OS.


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.


The are few issue in your assumptions.

First of all the SecureString class does not have a String constructor. In order to create one you allocate an object and then append the chars.

In the case of a GUI or a console, you can very easily pass each pressed key to a secure string.

The class is designed in a way that you cannot, by mistake, access the value that is stored. This means that you can not obtain the string as a password directly from it.

So for using it, for example, to authenticate through the web, you will have to use proper classes that are also secure.

In the .NET framework you have a few classes that can use SecureString

  • WPF's PasswordBox control keeps the password as a SecureString internally.
  • System.Diagnostics.ProcessInfo's Password property is a SecureString.
  • The constructor for X509Certificate2 takes a SecureString for the password.

(more)

To conclude, the SecureString class can be useful, but requires more attention from the developer.

All this, with examples, is well described in MSDN's documentation of SecureString


A SecureString is useful if:

  • You build it character by character (e.g. from console input) or obtain it from an unmanaged API

  • You use it by passing it to an unmanaged API (SecureStringToBSTR).

If you ever convert it to a managed string, you've defeated its purpose.

UPDATE in response to comment

... or BSTR like you mention, which doesn't seem any more secure

After its been converted to a BSTR, the unmanaged component that consumes the BSTR can zero the memory. Unmanaged memory is more secure in the sense that it can be reset in this way.

However, there are very few, APIs in the .NET Framework that support SecureString, so you're right to say that it's of very limited value today.

The main use case I would see is in a client application that requires the user to enter a highly sensitive code or password. The user input could be used character by character to build a SecureString, then this could be passed to an unmanaged API, which zeroes the BSTR it receives after using it. Any subsequent memory dump will not contain the sensitive string.

In a server application it's hard to see where it would be useful.

UPDATE 2

One example of a .NET API that accepts a SecureString is this constructor for the X509Certificate class. If you spelunk with ILSpy or similar, you'll see that the SecureString is internally converted to an unmanaged buffer (Marshal.SecureStringToGlobalAllocUnicode), which is then zeroed when finished with (Marshal.ZeroFreeGlobalAllocUnicode).


Microsoft does not recommend to use SecureString for newer codes.

From documentation of SecureString Class:

Important

We don't recommend that you use the SecureString class for new development. For more information, see SecureString shouldn't be used

Which recommends:

Don't use SecureString for new code. When porting code to .NET Core, consider that the contents of the array are not encrypted in memory.

The general approach of dealing with credentials is to avoid them and instead rely on other means to authenticate, such as certificates or Windows authentication. on GitHub.


As you have correctly identified, SecureString offers one specific advantage over string: deterministic erasure. There are two problems with this fact:

  1. As others have mentioned and as you have noticed by yourself, this isn't enough by itself. You have to make sure that every step of the process (including retrieval of input, construction of the string, usage, deletion, transportation, etc) happens without defeating the purpose of using SecureString. This means that you must be careful to never create a GC-managed immutable string or any other buffer that will store the sensitive information (or you'll have to keep track of that as well). In practice, this isn't always easy to achieve, because lots of APIs only offer a way to work with string, not SecureString. And even if you do manage to everything right...
  2. SecureString protects against very specific kinds of attack (and for some of them, it's not even that reliable). For example, SecureString does allow you to shrink the time window in which an attacker can dump the memory of your process and successfully extract the sensitive information (again, as you correctly pointed out), but hoping that the window is too small for the attacker to take a snapshot of your memory isn't considered security at all.

So, when should you use it? Only when you're working with something that can allow you to work with SecureString for all your needs and even then you should still be mindful that this is secure only in specific circumstances.


Below text is copied from HP Fortify static code analyzer

Abstract: The method PassString() in PassGenerator.cs stores sensitive data in an insecure manner (i.e. in string), making it possible to extract the data via inspecting the heap.

Explanation: Sensitive data (such as passwords, social security numbers, credit card numbers etc.) stored in memory can be leaked if it is stored in a managed String object. String objects are not pinned, so the garbage collector can relocate these objects at will and leave several copies in memory. These objects are not encrypted by default, so anyone who can read the process' memory will be able to see the contents. Furthermore, if the process' memory gets swapped out to disk, the unencrypted contents of the string will be written to a swap file. Lastly, since String objects are immutable, removing the value of a String from memory can only be done by the CLR garbage collector. The garbage collector is not required to run unless the CLR is low on memory, so there is no guarantee as to when garbage collection will take place. In the event of an application crash, a memory dump of the application might reveal sensitive data.

Recommendations: Instead of storing sensitive data in objects like Strings, store them in a SecureString object. Each object stores its contents in an encrypted format in memory at all times.


I'd like to address this point:

If an attacker already has the means for a heap inspection, then they most likely either (A) already have the means to read keystrokes, or (B) already physically have the machine... So would using a SecureString prevent them from getting to the data anyways?

An attacker may not have full access to the computer and the application but can have means to access some parts of the memory of the process. It is usually caused by bugs like buffer overruns when specially constructed input can cause the application to expose or overwrite some part of the memory.

HeartBleed leaking memory

Take Heartbleed for example. Specially constructed requests can cause the code to expose random parts of the memory of the process to the attacker. An attacker can extract SSL certificates from the memory, yet the only thing he needs is just to use a malformed request.

In the world of the managed code, buffer overruns become a problem much less often. And in case of WinForms, data is already stored in an insecure manner and you can't do anything about it. This renders the protection with SecureString pretty much useless.

However, GUI can be programmed to use SecureString, and in such case reducing the window of password availability in the memory can be worth it. For example, PasswordBox.SecurePassword from WPF is of type SecureString.