<commit_before>import struct
import ctypes
from ctypes import byref
import codecs
import functools

import windows
import windows.native_exec.simple_x86 as x86
import windows.native_exec.simple_x64 as x64
from .generated_def.winstructs import *
from windows.winobject import process
from windows import winproxy
from .winproxy import NeededParameter

# Special code for syswow64 process
CS_32bits = 0x23
CS_64bits = 0x33


def generate_64bits_execution_stub_from_syswow(x64shellcode):
    """shellcode must NOT end by a ret"""
    current_process = windows.current_process
    if not current_process.is_wow_64:
        raise ValueError("Calling generate_64bits_execution_stub_from_syswow from non-syswow process")

    transition64 = x64.MultipleInstr()
    transition64 += x64.Call(":TOEXEC")
    transition64 += x64.Mov("RDX", "RAX")
    transition64 += x64.Shr("RDX", 32)
    transition64 += x64.Retf32()  # 32 bits return addr
    transition64 += x64.Label(":TOEXEC")
    x64shellcodeaddr = windows.current_process.allocator.write_code(transition64.get_code() + x64shellcode)

    transition =     x86.MultipleInstr()
    transition +=    x86.Call(CS_64bits, x64shellcodeaddr)
    # Reset the SS segment selector.
    # We need to do that due to a bug in AMD CPUs with RETF & SS
    # https://github.com/hakril/PythonForWindows/issues/10
    # http://blog.rewolf.pl/blog/?p=1484
    transition +=    x86.Mov("ECX", "SS")
    transition +=    x86.Mov("SS", "ECX")
    transition +=    x86.Ret()

    stubaddr = windows.current_process.allocator.write_code(transition.get_code())
    exec_stub = ctypes.CFUNCTYPE(ULONG64)(stubaddr)
    return exec_stub

def execute_64bits_code_from_syswow(x64shellcode):
    return generate_64bits_execution_stub_from_syswow(x64shellcode)()

def generate_syswow64_call(target, errcheck=None):
    nb_args = len(target.prototype._argtypes_)
    target_addr = get_syswow_ntdll_exports()[target.__name__]
    argument_buffer_len = (nb_args * 8)
    argument_buffer = windows.current_process.allocator.reserve_size(argument_buffer_len)
    alignement_information = windows.current_process.allocator.reserve_size(8)

    nb_args_on_stack = max(nb_args - 4, 0)

    code_64b = x64.MultipleInstr()
    # Save registers

    code_64b += x64.Push('RBX')
    code_64b += x64.Push('RCX')
    code_64b += x64.Push('RDX')
    code_64b += x64.Push('RSI')
    code_64b += x64.Push('RDI')
    code_64b += x64.Push('R8')
    code_64b += x64.Push('R9')
    code_64b += x64.Push('R10')
    code_64b += x64.Push('R11')
    code_64b += x64.Push('R12')
    code_64b += x64.Push('R13')

    # Alignment stuff :)
    code_64b += x64.Mov('RCX', 'RSP')
    code_64b += x64.And('RCX', 0x0f)
    code_64b += x64.Mov(x64.deref(alignement_information), 'RCX')
    code_64b += x64.Sub('RSP', 'RCX')
    # retrieve argument from the argument buffer
    if nb_args >= 1:
        code_64b += x64.Mov('RCX', x64.create_displacement(disp=argument_buffer))
    if nb_args >= 2:
        code_64b += x64.Mov('RDX', x64.create_displacement(disp=argument_buffer + (8 * 1)))
    if nb_args >= 3:
        code_64b += x64.Mov('R8', x64.create_displacement(disp=argument_buffer + (8 * 2)))
    if nb_args >= 4:
        code_64b += x64.Mov('R9', x64.create_displacement(disp=argument_buffer + (8 * 3)))
    for i in range(nb_args_on_stack):
        code_64b += x64.Mov('RAX',  x64.create_displacement(disp=argument_buffer + 8 * (nb_args - 1 - i)))
        code_64b += x64.Push('RAX')
    # reserve space for register (calling convention)
    code_64b += x64.Push('R9')
    code_64b += x64.Push('R8')
    code_64b += x64.Push('RDX')
    code_64b += x64.Push('RCX')
    # Call
    code_64b += x64.Mov('R13', target_addr)
    code_64b += x64.Call('R13')
    # Realign stack :)
    code_64b += x64.Add('RSP', x64.deref(alignement_information))
    # Clean stack
    code_64b += x64.Add('RSP', (4 + nb_args_on_stack) * 8)
    code_64b += x64.Pop('R13')
    code_64b += x64.Pop('R12')
    code_64b += x64.Pop('R11')
    code_64b += x64.Pop('R10')
    code_64b += x64.Pop('R9')
    code_64b += x64.Pop('R8')
    code_64b += x64.Pop('RDI')
    code_64b += x64.Pop('RSI')
    code_64b += x64.Pop('RDX')
    code_64b += x64.Pop('RCX')
    code_64b += x64.Pop('RBX')
    code_64b += x64.Ret()
    return try_generate_stub_target(code_64b.get_code(), argument_buffer, target, errcheck=errcheck)


def try_generate_stub_target(shellcode, argument_buffer, target, errcheck=None):
    if not windows.current_process.is_wow_64:
        raise ValueError("Calling execute_64bits_code_from_syswow from non-syswow process")
    native_caller = generate_64bits_execution_stub_from_syswow(shellcode)
    native_caller.errcheck = errcheck if errcheck is not None else target.errcheck
    # Generate the wrapper function that fill the argument_buffer
    expected_arguments_number = len(target.prototype._argtypes_)
    def wrapper(*args):
        if len(args) != expected_arguments_number:
            raise ValueError("{0} syswow accept {1} args ({2} given)".format(target.__name__, expected_arguments_number, len(args)))
        # Transform args (ctypes byref possibly) to int
        writable_args = []
        for i, value in enumerate(args):
            if not isinstance(value, (int, long)):
                try:
                    value = ctypes.cast(value, ctypes.c_void_p).value
                except ctypes.ArgumentError as e:
                    raise ctypes.ArgumentError("Argument {0}: wrong type <{1}>".format(i, type(value).__name__))
            writable_args.append(value)<commit_msg>Fix syswow64 32<->64 for python3-23b<commit_after>import struct
import ctypes
from ctypes import byref
import codecs
import functools

import windows
import windows.native_exec.simple_x86 as x86
import windows.native_exec.simple_x64 as x64
from .generated_def.winstructs import *
from windows.winobject import process
from windows import winproxy
from .winproxy import NeededParameter
from .pycompat import int_types

# Special code for syswow64 process
CS_32bits = 0x23
CS_64bits = 0x33


def generate_64bits_execution_stub_from_syswow(x64shellcode):
    """shellcode must NOT end by a ret"""
    current_process = windows.current_process
    if not current_process.is_wow_64:
        raise ValueError("Calling generate_64bits_execution_stub_from_syswow from non-syswow process")

    transition64 = x64.MultipleInstr()
    transition64 += x64.Call(":TOEXEC")
    transition64 += x64.Mov("RDX", "RAX")
    transition64 += x64.Shr("RDX", 32)
    transition64 += x64.Retf32()  # 32 bits return addr
    transition64 += x64.Label(":TOEXEC")
    x64shellcodeaddr = windows.current_process.allocator.write_code(transition64.get_code() + x64shellcode)

    transition =     x86.MultipleInstr()
    transition +=    x86.Call(CS_64bits, x64shellcodeaddr)
    # Reset the SS segment selector.
    # We need to do that due to a bug in AMD CPUs with RETF & SS
    # https://github.com/hakril/PythonForWindows/issues/10
    # http://blog.rewolf.pl/blog/?p=1484
    transition +=    x86.Mov("ECX", "SS")
    transition +=    x86.Mov("SS", "ECX")
    transition +=    x86.Ret()

    stubaddr = windows.current_process.allocator.write_code(transition.get_code())
    exec_stub = ctypes.CFUNCTYPE(ULONG64)(stubaddr)
    return exec_stub

def execute_64bits_code_from_syswow(x64shellcode):
    return generate_64bits_execution_stub_from_syswow(x64shellcode)()

def generate_syswow64_call(target, errcheck=None):
    nb_args = len(target.prototype._argtypes_)
    target_addr = get_syswow_ntdll_exports()[target.__name__]
    argument_buffer_len = (nb_args * 8)
    argument_buffer = windows.current_process.allocator.reserve_size(argument_buffer_len)
    alignement_information = windows.current_process.allocator.reserve_size(8)

    nb_args_on_stack = max(nb_args - 4, 0)

    code_64b = x64.MultipleInstr()
    # Save registers

    code_64b += x64.Push('RBX')
    code_64b += x64.Push('RCX')
    code_64b += x64.Push('RDX')
    code_64b += x64.Push('RSI')
    code_64b += x64.Push('RDI')
    code_64b += x64.Push('R8')
    code_64b += x64.Push('R9')
    code_64b += x64.Push('R10')
    code_64b += x64.Push('R11')
    code_64b += x64.Push('R12')
    code_64b += x64.Push('R13')

    # Alignment stuff :)
    code_64b += x64.Mov('RCX', 'RSP')
    code_64b += x64.And('RCX', 0x0f)
    code_64b += x64.Mov(x64.deref(alignement_information), 'RCX')
    code_64b += x64.Sub('RSP', 'RCX')
    # retrieve argument from the argument buffer
    if nb_args >= 1:
        code_64b += x64.Mov('RCX', x64.create_displacement(disp=argument_buffer))
    if nb_args >= 2:
        code_64b += x64.Mov('RDX', x64.create_displacement(disp=argument_buffer + (8 * 1)))
    if nb_args >= 3:
        code_64b += x64.Mov('R8', x64.create_displacement(disp=argument_buffer + (8 * 2)))
    if nb_args >= 4:
        code_64b += x64.Mov('R9', x64.create_displacement(disp=argument_buffer + (8 * 3)))
    for i in range(nb_args_on_stack):
        code_64b += x64.Mov('RAX',  x64.create_displacement(disp=argument_buffer + 8 * (nb_args - 1 - i)))
        code_64b += x64.Push('RAX')
    # reserve space for register (calling convention)
    code_64b += x64.Push('R9')
    code_64b += x64.Push('R8')
    code_64b += x64.Push('RDX')
    code_64b += x64.Push('RCX')
    # Call
    code_64b += x64.Mov('R13', target_addr)
    code_64b += x64.Call('R13')
    # Realign stack :)
    code_64b += x64.Add('RSP', x64.deref(alignement_information))
    # Clean stack
    code_64b += x64.Add('RSP', (4 + nb_args_on_stack) * 8)
    code_64b += x64.Pop('R13')
    code_64b += x64.Pop('R12')
    code_64b += x64.Pop('R11')
    code_64b += x64.Pop('R10')
    code_64b += x64.Pop('R9')
    code_64b += x64.Pop('R8')
    code_64b += x64.Pop('RDI')
    code_64b += x64.Pop('RSI')
    code_64b += x64.Pop('RDX')
    code_64b += x64.Pop('RCX')
    code_64b += x64.Pop('RBX')
    code_64b += x64.Ret()
    return try_generate_stub_target(code_64b.get_code(), argument_buffer, target, errcheck=errcheck)


def try_generate_stub_target(shellcode, argument_buffer, target, errcheck=None):
    if not windows.current_process.is_wow_64:
        raise ValueError("Calling execute_64bits_code_from_syswow from non-syswow process")
    native_caller = generate_64bits_execution_stub_from_syswow(shellcode)
    native_caller.errcheck = errcheck if errcheck is not None else target.errcheck
    # Generate the wrapper function that fill the argument_buffer
    expected_arguments_number = len(target.prototype._argtypes_)
    def wrapper(*args):
        if len(args) != expected_arguments_number:
            raise ValueError("{0} syswow accept {1} args ({2} given)".format(target.__name__, expected_arguments_number, len(args)))
        # Transform args (ctypes byref possibly) to int
        writable_args = []
        for i, value in enumerate(args):
            if not isinstance(value, int_types):
                try:
                    value = ctypes.cast(value, ctypes.c_void_p).value
                except ctypes.ArgumentError as e:
                    raise ctypes.ArgumentError("Argument {0}: wrong type <{1}>".format(i, type(value).__name__))
            writable_args.append(value)
{'fraction_non_alphanumeric': 0.12507817385866166, 'fraction_numerical': 0.0613776467435004, 'mean_word_length': 3.68172312839816, 'pattern_counts': {'":': 4, '<': 6, '<?xml version=': 0, '>': 14, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2599724', 'n_tokens_mistral': 4376, 'n_tokens_neox': 3967, 'n_words': 774}