0

If I do the following in a class, is my password cached/discoverable in memory?

public class ConnectionInfo
    {
        private SecureString _password;
        public string UserName;

        public string Password
        {
            get
            {
                IntPtr valuePtr = IntPtr.Zero;
                try
                {
                    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(_password);
                    return Marshal.PtrToStringUni(valuePtr);
                }
                finally
                {
                    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
                }
            }
            set
            {
                _password = new SecureString();
                foreach (char c in value)
                {
                    _password.AppendChar(c);
                }
            }
        }
    }

In other words, if I use it like this

ConnectionInfo connectionInfo = new Models.DomainInfo();
connectionInfo.Password = "Password1";

and later use it with a directoryEntry

DirectoryEntry entry = new DirectoryEntry("LDAP://Domain.com", $"Domain\\{connectionInfo.UserName}", connectionInfo.Password);

is the cleartext password cached via the property Password? (I am not referring to any leaks that might occur via DirectoryEntry etc., only the Property)

Password is stored in web/app.config and retrieved via this

staticKey = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(stringToDecrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(staticKey, staticIV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());

Is the encryption strong enough?

Shaun Vermaak
  • 301
  • 2
  • 13
  • 1
    Btw. see https://stackoverflow.com/a/26202992/1336590 on the purpose of `SecureString`. It's basically protection against stupidity. Not actually all that "secure". – Corak May 09 '19 at 07:50

1 Answers1

1

The answer is complicated - yes, the Property itself is secure, there is no caching done. BUT - the string returned will be managed by the Garbage Collector and exist until garbage collected.

I honestly do not thing SecureString is all that worthwile. It somewhat protects against analysing a memory dump, but it only shortens the threat window. Since input und usage are usually plain old strings, the password WILL show up in the memory dump sooner or later.

Also, how do you get the password to the application? That's usually the part where an attacker can get the PW.

Christian Sauer
  • 10,351
  • 10
  • 53
  • 85