Heap Inspection
成因
將敏感性資料(身分證號、密碼)儲存在 String 物件中,無法確實的由記憶體中清除。
因 String 物件為不可變,只能透過程式語言的記憶體回收機制(Garbage Collection,GC)進行清除,但 String 物件即使不再使用,也不一定會馬上會被GC回收,也就是說我們無法確保敏感性資料是被清除,還是仍留在記憶體中。在應用程式意外結束時,應用程式的記憶體傾印即可能洩露敏感性資料;或是透過某些工具,也可以取得應用程式在記憶體中的資料。
解決方法
有一個簡單的方法可以解決問題,就是用 Char[] 取代 String。但在 .Net 應用程式,提供了 System.Security.SecureString 類別讓我們使用,SecureString 的資料在記憶體中是加密的,且可設為唯讀,避免被修改。我們可用 SecureString 保存保敏感性資料,以減少機密資料在記憶體中的時間,降低被竊取的風險。
String 與 SecureString 之間的轉換函數如下
private static SecureString getPwdSecurity(string value)
{
SecureString result = new SecureString();
foreach (char c in value)
{
result.AppendChar(c);
}
return result;
}
private static string SecureStringToString(SecureString value)
{
IntPtr valuePtr = IntPtr.Zero;
try
{
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
return Marshal.PtrToStringUni(valuePtr);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
在解決專案件的Hepa Inspection,把引起問題的函數改為如下
public static byte[] SetSecurity(byte[] content, SecureString ownerPassword, SecureString newOwnerPassword,
SecureString newUserPassword, bool canPrint, bool canCopy)
{
//do something
}
將 String 改為 SecureString 來解決此問題。
留言
張貼留言