Building Your Own Module
193
# Our payload converter grabs a hex file and converts it to binary through PowerShell
h2b
= "$s = gc 'C:\\Windows\\Temp\\#{
var_payload
}';$s = [string]::Join('', $s);$s=
$s.
Replace('`r',''); $s = $s.Replace(''`n','');$b = new-object byte[] $($s.Length/
2);0..$($b.Length-1) | %{$b[$_] = [Convert]::ToByte($s.Substring($($_*2),2),16)};
[IO.File]::WriteAllBytes('C:\\Windows\\Temp\\#{
var_payload
}.exe',$b)"
h2b_unicode=Rex::Text.to_unicode(h2b)
# base64 encoding allows us to perform execution through powershell without registry changes
h2b_encoded = Rex::Text.encode_base64(h2b_unicode)
print_status("Uploading the payload #{var_payload}, please be patient...")
At we create the hex-to-binary (
h2b
) conversion method through
PowerShell. This code essentially creates a byte array that will write out the
hex-based Metasploit payload as a binary file. (The
{var_payload}
is a random
name specified through Metasploit.)
Because MS SQL has character limit restrictions, we need to break our
hexadecimal payload into 500-byte chunks that separate the payload into
multiple requests. But one side effect of this splitting is that carriage returns
and line feeds (CRLF) are added to the file on the target, and these need to
be stripped out. At we add better handling of CRLFs by stripping them out
properly. If we didn’t do this, our binary would be corrupt and would not
execute properly. Notice that we are simply redesignating the
$s
variable to
replace
`r
and
`n
with
''
(nothing). This effectively removes CRLFs.
Once the CRLFs are stripped out,
Convert::ToByte
is invoked in the hex-
based Metasploit payload. We tell PowerShell that the file’s format is base 16
(hexadecimal format) and to write it out to a file called
#{var_payload}.exe
(our random payload name). After the payload has been written, we can run
a method for executing PowerShell commands in an encoded format that is
supported by the PowerShell programming language. These encoded com-
mands allow us to execute lengthy and large amounts of code on one line.
By first converting the
h2b
string at to Unicode and then Base64
encoding the resultant string at , we can pass the
–EncodedCommand
flag
through PowerShell to bypass execution restrictions that would normally
exist. The execution restriction policies do not allow untrusted scripts to be
executed. (These restrictions are an important way to protect users from exe-
cuting just any script they download on the Internet.) If we didn’t encode
these commands, we wouldn’t be able to execute our PowerShell code and
ultimately wouldn’t be able to compromise the target system. Encoding the
commands allow us to add lots of code to one command without worrying
about execution restriction policies.
After we specified the
h2b
string and encoded command flags, we get the
PowerShell commands in the correct encoded format so that we can execute
our PowerShell code in an unrestricted format.