0

currently I have issue on project where secure string is exposed like this:

IntPtr unmanagedString = IntPtr.Zero;
try
{
        unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
        string str = Marshal.PtrToStringUni(unmanagedString);
        ...
        ...
}
finally
{
        Marshal.ZeroFreeGlobalAllocUnicode(ptr);
}

After Marshal.SecureStringToGlobalAllocUnicode(secureString) call, copy of secure string content is saved in unmanaged memory. Even after Marshal.ZeroFreeGlobalAllocUnicode(ptr) is called string can be easily found with memory tools, by simply searching for all strings.

Is there a way to completely remove it or at least go around it in some way, like overwrite it?

Dudeson
  • 41
  • 1
  • 8
  • You may be *zeroing the memory*, but what about the other memory you allocated with with `string str = Marshal.PtrToStringUni(unmanagedString);` in fact every time you modify the string its going to create more copies. The rule of thumb is *"if you want to keep things secure, don't put them in apps that people can rummage through"* – TheGeneral Feb 04 '20 at 09:35
  • 2
    (disclaimer: I never worked with `SecureString`; or pointers in C# for that matter) - does this help? https://stackoverflow.com/a/3567531/1336590 -- as far as I understood, `SecureString` saves you from stupid mistakes (dump to logfile or something similar). But as soon as a `string` instance is created, that's it. Now it's in memory for "everyone" to read. – Corak Feb 04 '20 at 09:35
  • As I have tested, ```string str``` gets garbage collated later on. However ```unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);``` creates instance in unmanaged memory, where garbage do not work. While clearing this manually do not seem to take any effect. – Dudeson Feb 04 '20 at 09:42
  • Also I will test this class out, maybe it will help. – Dudeson Feb 04 '20 at 09:44
  • `ZeroFreeGlobalAllocUnicode` will call `ZeroMemory` and it will clear the memory allocated by `SecureStringToGlobalAllocUnicode`. there are other reasons why managed memory will hang around after the GC – TheGeneral Feb 04 '20 at 09:53
  • @Corak Thanks, this seems to work! [solution](http://stackoverflow.com/a/3567531/1336590) – Dudeson Feb 04 '20 at 10:00

0 Answers0