문제

I am trying to remove any traces of a normal string from memory, to do so I am creating an instance of SecureString from a reference of the normal string. Like so:

public static unsafe void Burn(this string input)
{
    fixed (char* c = input)
    {
        var secure = new SecureString(c, input.Length);
        secure.Dispose();
    }
}

The problem is that even after calling the dispose method the contents of input are non-changed. From my understanding the SecureString instance should reference the input address and therefore clean if from memory upon Dispose() call. What am I missing?

도움이 되었습니까?

해결책

It appears the two parameter constructor is not meant to be used by your code. The documentation isn't clear but its use of the phrase Initializes a new instance of the SecureString class from a subarray of System.Char objects tells me it's probably copying the data, not encrypting the existing string in place. This would make sense since the documentation for SecureString specifically mentions a String cannot be destroyed in a deterministic way.

A good way to test this theory would be to compare the addresses of input and secure to see if they still point to the same location in memory after the initialization.

다른 팁

string objects are shared. Who knows what is code is referencing that input string? Security decisions could be based on it.

Therefore, strings must always be immutable in .NET. You cannot kill its contents (in a documented way).

input might even refer to a string literal! If you change its contents, literals in unrelated code might change their value. You write "x" and get "\0" at runtime. This is so horrible.

Furthermore, the GC can move objects around. Your secret data has probably leaked all over the heap already. Construct your app in such a way that it does not require destroying data, or only store it in pinned/unmanaged buffers.

This isn't really meant as an answer as there is no way to determine that the string isn't still floating in memory somewhere, but I thought I would post this because it does modify the original string that it was called on.


public static class StringTest
{
    public static unsafe void Burn(this string input)
    {
        fixed (char* c = input)
        {
            Marshal.Copy(new string('\0', input.Length).ToCharArray(), 0, new IntPtr(c), input.Length);
        }
    }
}

Testing your sample code, I was able to come up with this. No guarantees that it doesn't leak memory, but it does "burn" the calling string. Your string may still be floating in memory somewhere else though.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top