經得起原始碼資安弱點掃描的程式設計習慣培養(十)_Heap Inspection

 

  接續前幾篇系列















風險:
應用程式在未加密的memory中存儲的所有變數都可能被主機特權User(privileged access)未經授權的檢索。
例如,特權攻擊者可以對正在執行的process掛上debugger,也可能從swapfile
或crash dump file中檢索process's memory。一旦攻擊者
在Memory中找到User的密碼,就可以輕鬆的假冒User進入系統。




如何避免:
字串變數是不變的(immutable)
換言之,一旦分配了字串變數,就無法更改或刪除其值。
因此,這些字串可能會無限期的留存在memory中,而且
可能分散在多個位置中,直到垃圾收集器(garbage collector)將其刪除。
敏感資料,例如密碼,將作為明文在memory中暴露,無法控制其生命週期。


不要將敏感資料(如password或encryption key)以明文形式存儲在memory中,時間再短都不要。
建議使用專為store encrypted memory設計的Class。
或者,將機敏資料存在可變類型中(如byte array),使用完立即將array中每個byte位歸零。
在.NET中,不要將密碼儲存在不可變的string中,
建議使用encrypted memoryobject,例如SecureString或ProtectedData。



這裡只需要透過SecureString來存放即可避免該風險
也可以封裝extension method來解省後續重複寫很多修正code的部分

extension method用上癮了

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Web;

/// <summary>
/// SecureStringExtension 的摘要描述
/// </summary>
public static class SecureStringExtension
{
    public static SecureString GetSecureString(this string val)
    {
        SecureString result = new SecureString();
        foreach (Char ch in val)
        {
            result.AppendChar(ch);
        }
        return result;
        result.Dispose();
        result.Clear();
    }



    public static string SecureStrToString(this SecureString val)
    {
        IntPtr ptrVal = IntPtr.Zero;
        try
        {
            ptrVal = Marshal.SecureStringToGlobalAllocUnicode(val);
            return Marshal.PtrToStringUni(ptrVal);
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            Marshal.ZeroFreeGlobalAllocUnicode(ptrVal);
        }
    }


}








留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients