[
  {
    "path": "IDA_plugin/param_enum.py",
    "content": "\"\"\"\nReplace immediate values push before a call by enum value\n\"\"\"\n\nfrom idc import *\nfrom idaapi import *\nfrom idautils import *\nfrom ida_enum import *\n\ndef replace_pushed_int(function_ea, target_push_n, target_enum_name, before_limit=0x30, int_type=\"hex\"):\n    \"\"\"\n    Replace the <target_push_n> last immediate value push before by enum value if possible\n\n    function_ea : target function ea (will check Xref to this ea)\n                  for structs use get_name_ea_simple\n    target_push_n : how many push back we want, starts at 1\n    target_enum_name : enum to target (created if doesn't exists)\n    before_limit : how much back we agree to go\n    str_type : \"hex\" or \"dec\", used for the enum value names (in hex or dec number)\n    \"\"\"\n\n    target_enum = get_enum(target_enum_name)\n    if target_enum == BADADDR:\n        if int_type == \"hex\":\n            target_enum = add_enum(0, target_enum_name, hex_flag())\n        else:\n            target_enum = add_enum(0, target_enum_name, dec_flag())\n\n    for xref in XrefsTo(function_ea, 0):\n        current_ea = xref.frm\n        push_n = 0\n        \n        while current_ea != BADADDR:\n            current_ea = prev_head(current_ea, xref.frm - before_limit)\n            \n            if print_insn_mnem(current_ea) == \"push\":\n                push_n += 1\n\n                if push_n == target_push_n: # that's the push we are looking for\n\n                    type_n = get_operand_type(current_ea, 0)\n                    if type_n == 5: # immediate value\n                        value = get_operand_value(current_ea, 0)\n                       \n                        enum_value = get_enum_member(target_enum, value, 0, 0)\n                        if enum_value == BADADDR:\n                            # Create a new enum value\n                            if int_type == \"hex\":\n                                enum_val_name = \"{:02X}\".format(value)\n                            else:\n                                enum_val_name = str(value)\n\n                            enum_value = add_enum_member(target_enum, get_enum_name(target_enum) + \"_\" + enum_val_name, value)\n\n                        op_enum(current_ea, 0, target_enum, 0)\n\n                    else: # not an immediate value\n                        print(f\"Help needed @ {hex(current_ea)}\")\n                    \n                    break # Done here, break to the next Xref\n"
  },
  {
    "path": "README.md",
    "content": "Collection of tools developped by myself.\n\nSome of them may have articles describing them on my [blog](https://bidouillesecurity.com)"
  },
  {
    "path": "disable-defender.ps1",
    "content": "# Disable Windows Defender\r\n\r\n<#\r\n                           _               _ \r\n __      ____ _ _ __ _ __ (_)_ __   __ _  | |\r\n \\ \\ /\\ / / _` | '__| '_ \\| | '_ \\ / _` | | |\r\n  \\ V  V / (_| | |  | | | | | | | | (_| | |_|\r\n   \\_/\\_/ \\__,_|_|  |_| |_|_|_| |_|\\__, | (_)\r\n                                   |___/     \r\n\r\nThis script is NOT a disable/enable solution, I'm a malware analyst, I use it for malware analysis.\r\nIt can completely DELETE Defender, and it is NOT REVERSIBLE (that's what I need).\r\nOnce you have run it, you will no longer have any sort of antivirus protection, and WILL NOT BE ABLE to reactivate it.\r\n\r\nThink twice before running it, or read the blog post to understand and modify it to suit **your** needs.\r\n\r\nTHIS IS NOT A JOKE.\r\nYOU HAVE BEEN WARNED.\r\n#>\r\n\r\n<#\r\nOptions :\r\n\r\n-Delete : delete the defender related files (services, drivers, executables, ....) \r\n\r\nSource :  https://bidouillesecurity.com/disable-windows-defender-in-powershell\r\n\r\n#>\r\n\r\nWrite-Host \"[+] Disable Windows Defender (as $(whoami))\"\r\n\r\n\r\n## STEP 0 : elevate if needed\r\n\r\n\r\nif(-Not $($(whoami) -eq \"nt authority\\system\")) {\r\n    $IsSystem = $false\r\n\r\n    # Elevate to admin (needed when called after reboot)\r\n    if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {\r\n        Write-Host \"    [i] Elevate to Administrator\"\r\n        $CommandLine = \"-ExecutionPolicy Bypass `\"\" + $MyInvocation.MyCommand.Path + \"`\" \" + $MyInvocation.UnboundArguments\r\n        Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine\r\n        Exit\r\n    }\r\n\r\n    # Elevate to SYSTEM if psexec is available\r\n    $psexec_path = $(Get-Command PsExec -ErrorAction 'ignore').Source \r\n    if($psexec_path) {\r\n        Write-Host \"    [i] Elevate to SYSTEM\"\r\n        $CommandLine = \" -i -s powershell.exe -ExecutionPolicy Bypass `\"\" + $MyInvocation.MyCommand.Path + \"`\" \" + $MyInvocation.UnboundArguments \r\n        Start-Process -WindowStyle Hidden -FilePath $psexec_path -ArgumentList $CommandLine\r\n        exit\r\n    } else {\r\n        Write-Host \"    [i] PsExec not found, will continue as Administrator\"\r\n    }\r\n\r\n} else {\r\n    $IsSystem = $true\r\n}\r\n\r\n\r\n## STEP 1 : Disable everything we can with immediate effect\r\n\r\n\r\nWrite-Host \"    [+] Add exclusions\"\r\n\r\n# Add the whole system in Defender exclusions\r\n\r\n67..90|foreach-object{\r\n    $drive = [char]$_\r\n    Add-MpPreference -ExclusionPath \"$($drive):\\\" -ErrorAction SilentlyContinue\r\n    Add-MpPreference -ExclusionProcess \"$($drive):\\*\" -ErrorAction SilentlyContinue\r\n}\r\n\r\nWrite-Host \"    [+] Disable scanning engines (Set-MpPreference)\"\r\n\r\nSet-MpPreference -DisableArchiveScanning 1 -ErrorAction SilentlyContinue\r\nSet-MpPreference -DisableBehaviorMonitoring 1 -ErrorAction SilentlyContinue\r\nSet-MpPreference -DisableIntrusionPreventionSystem 1 -ErrorAction SilentlyContinue\r\nSet-MpPreference -DisableIOAVProtection 1 -ErrorAction SilentlyContinue\r\nSet-MpPreference -DisableRemovableDriveScanning 1 -ErrorAction SilentlyContinue\r\nSet-MpPreference -DisableBlockAtFirstSeen 1 -ErrorAction SilentlyContinue\r\nSet-MpPreference -DisableScanningMappedNetworkDrivesForFullScan 1 -ErrorAction SilentlyContinue\r\nSet-MpPreference -DisableScanningNetworkFiles 1 -ErrorAction SilentlyContinue\r\nSet-MpPreference -DisableScriptScanning 1 -ErrorAction SilentlyContinue\r\nSet-MpPreference -DisableRealtimeMonitoring 1 -ErrorAction SilentlyContinue\r\n\r\nWrite-Host \"    [+] Set default actions to Allow (Set-MpPreference)\"\r\n\r\nSet-MpPreference -LowThreatDefaultAction Allow -ErrorAction SilentlyContinue\r\nSet-MpPreference -ModerateThreatDefaultAction Allow -ErrorAction SilentlyContinue\r\nSet-MpPreference -HighThreatDefaultAction Allow -ErrorAction SilentlyContinue\r\n\r\n\r\n## STEP 2 : Disable services, we cannot stop them, but we can disable them (they won't start next reboot)\r\n\r\n\r\nWrite-Host \"    [+] Disable services\"\r\n\r\n$need_reboot = $false\r\n\r\n# WdNisSvc Network Inspection Service \r\n# WinDefend Antivirus Service\r\n# Sense : Advanced Protection Service\r\n\r\n$svc_list = @(\"WdNisSvc\", \"WinDefend\", \"Sense\")\r\nforeach($svc in $svc_list) {\r\n    if($(Test-Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\$svc\")) {\r\n        if( $(Get-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\$svc\").Start -eq 4) {\r\n            Write-Host \"        [i] Service $svc already disabled\"\r\n        } else {\r\n            Write-Host \"        [i] Disable service $svc (next reboot)\"\r\n            Set-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\$svc\" -Name Start -Value 4\r\n            $need_reboot = $true\r\n        }\r\n    } else {\r\n        Write-Host \"        [i] Service $svc already deleted\"\r\n    }\r\n}\r\n\r\nWrite-Host \"    [+] Disable drivers\"\r\n\r\n# WdnisDrv : Network Inspection System Driver\r\n# wdfilter : Mini-Filter Driver\r\n# wdboot : Boot Driver\r\n\r\n$drv_list = @(\"WdnisDrv\", \"wdfilter\", \"wdboot\")\r\nforeach($drv in $drv_list) {\r\n    if($(Test-Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\$drv\")) {\r\n        if( $(Get-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\$drv\").Start -eq 4) {\r\n            Write-Host \"        [i] Driver $drv already disabled\"\r\n        } else {\r\n            Write-Host \"        [i] Disable driver $drv (next reboot)\"\r\n            Set-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\$drv\" -Name Start -Value 4\r\n            $need_reboot = $true\r\n        }\r\n    } else {\r\n        Write-Host \"        [i] Driver $drv already deleted\"\r\n    }\r\n}\r\n\r\n# Check if service running or not\r\nif($(GET-Service -Name WinDefend).Status -eq \"Running\") {   \r\n    Write-Host \"    [+] WinDefend Service still running (reboot required)\"\r\n    $need_reboot = $true\r\n} else {\r\n    Write-Host \"    [+] WinDefend Service not running\"\r\n}\r\n\r\n\r\n## STEP 3 : Reboot if needed, add a link to the script to Startup (will be runned again after reboot)\r\n\r\n\r\n$link_reboot = \"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\disable-defender.lnk\"\r\nRemove-Item -Force \"$link_reboot\" -ErrorAction 'ignore' # Remove the link (only execute once after reboot)\r\n\r\nif($need_reboot) {\r\n    Write-Host \"    [+] This script will be started again after reboot.\" -BackgroundColor DarkRed -ForegroundColor White\r\n    \r\n    $powershell_path = '\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\"'\r\n    $cmdargs = \"-ExecutionPolicy Bypass `\"\" + $MyInvocation.MyCommand.Path + \"`\" \" + $MyInvocation.UnboundArguments\r\n    \r\n    $res = New-Item $(Split-Path -Path $link_reboot -Parent) -ItemType Directory -Force\r\n    $WshShell = New-Object -comObject WScript.Shell\r\n    $shortcut = $WshShell.CreateShortcut($link_reboot)\r\n    $shortcut.TargetPath = $powershell_path\r\n    $shortcut.Arguments = $cmdargs\r\n    $shortcut.WorkingDirectory = \"$(Split-Path -Path $PSScriptRoot -Parent)\"\r\n    $shortcut.Save()\r\n\r\n} else {\r\n\r\n\r\n    ## STEP 4 : After reboot (we checked that everything was successfully disabled), make sure it doesn't come up again !\r\n\r\n\r\n    if($IsSystem) {\r\n\r\n        # Configure the Defender registry to disable it (and the TamperProtection)\r\n        # editing HKLM:\\SOFTWARE\\Microsoft\\Windows Defender\\ requires to be SYSTEM\r\n\r\n        Write-Host \"    [+] Disable all functionnalities with registry keys (SYSTEM privilege)\"\r\n\r\n        # Cloud-delivered protection:\r\n        Set-ItemProperty -Path \"HKLM:\\SOFTWARE\\Microsoft\\Windows Defender\\Real-Time Protection\" -Name SpyNetReporting -Value 0\r\n        # Automatic Sample submission\r\n        Set-ItemProperty -Path \"HKLM:\\SOFTWARE\\Microsoft\\Windows Defender\\Real-Time Protection\" -Name SubmitSamplesConsent -Value 0\r\n        # Tamper protection\r\n        Set-ItemProperty -Path \"HKLM:\\SOFTWARE\\Microsoft\\Windows Defender\\Features\" -Name TamperProtection -Value 4\r\n        \r\n        # Disable in registry\r\n        Set-ItemProperty -Path \"HKLM:\\SOFTWARE\\Microsoft\\Windows Defender\" -Name DisableAntiSpyware -Value 1\r\n        Set-ItemProperty -Path \"HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\" -Name DisableAntiSpyware -Value 1\r\n\r\n    } else {\r\n        Write-Host \"    [W] (Optional) Cannot configure registry (not SYSTEM)\"\r\n    }\r\n\r\n\r\n    if($MyInvocation.UnboundArguments -And $($MyInvocation.UnboundArguments.tolower().Contains(\"-delete\"))) {\r\n        \r\n        # Delete Defender files\r\n\r\n        function Delete-Show-Error {\r\n            $path_exists = Test-Path $args[0]\r\n            if($path_exists) {\r\n                Remove-Item -Recurse -Force -Path $args[0]\r\n            } else {\r\n                Write-Host \"    [i] $($args[0]) already deleted\"\r\n            }\r\n        }\r\n\r\n        Write-Host \"\"\r\n        Write-Host \"[+] Delete Windows Defender (files, services, drivers)\"\r\n\r\n        # Delete files\r\n        Delete-Show-Error \"C:\\ProgramData\\Windows\\Windows Defender\\\"\r\n        Delete-Show-Error \"C:\\ProgramData\\Windows\\Windows Defender Advanced Threat Protection\\\"\r\n\r\n        # Delete drivers\r\n        Delete-Show-Error \"C:\\Windows\\System32\\drivers\\wd\\\"\r\n\r\n        # Delete service registry entries\r\n        foreach($svc in $svc_list) {\r\n            Delete-Show-Error \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\$svc\"\r\n        }\r\n\r\n        # Delete drivers registry entries\r\n        foreach($drv in $drv_list) {\r\n            Delete-Show-Error \"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\$drv\"\r\n        }\r\n    }\r\n}\r\n\r\nWrite-Host \"\"\r\nRead-Host -Prompt \"Press any key to continue\"\r\n"
  },
  {
    "path": "pin-unpacker/.gitignore",
    "content": "test/\nx64/\nx86/\nIAT.json\n*.exe\n*.dll\n.vs/"
  },
  {
    "path": "pin-unpacker/IAT.cpp",
    "content": "#include <iostream>\n#include <fstream>\n\n#include \"IAT.h\"\n#include \"utils.h\"\n\nusing std::endl;\n\nvoid IAT_add_library(IAT_table& table, char* DLL_Name, ADDRINT LoadLibrary_addr)\n{\n\tstruct IAT_DLL_entry& funct_entry = table[std::string(DLL_Name)];\n\tif (funct_entry.LoadLibrary_addr != 0) {\n\t\tfunct_entry.LoadLibrary_addr = LoadLibrary_addr;\n\t}\n}\n\nvoid IAT_add_function(IAT_table& table, char* DLL_Name, char* function_name, ADDRINT function_addr, ADDRINT GetProcAddress_addr)\n{\n\tstruct IAT_Func_entry entry;\n\tentry.Function_name = std::string(function_name);\n\tentry.IAT_RVA = function_addr;\n\tentry.GetProcAddress_addr = GetProcAddress_addr;\n\n\tstruct IAT_DLL_entry& funct_entry = table[std::string(DLL_Name)];\n\tfunct_entry.functions.push_back(entry);\n}\n\nvoid IAT_print(const IAT_table& table, std::ostream* out)\n{\n\t*out << \"=== IAT ===\" << endl;\n\tfor (std::pair<std::string, struct IAT_DLL_entry> element : table)\n\t{\n\t\t*out << element.first << \" (Loaded @ \" << int_to_hex(element.second.LoadLibrary_addr) << \")\" << endl;\n\t\tfor (struct IAT_Func_entry entry : element.second.functions)\n\t\t{\n\t\t\t*out << \"    \" << entry.Function_name << \" @ \" << int_to_hex(entry.IAT_RVA) << \" (Loaded @ \" << int_to_hex(entry.GetProcAddress_addr) << \")\" << endl;\n\t\t}\n\t}\n}\n\nvoid IAT_json_save(const IAT_table& table, const std::string& path)\n{\n\tstd::ofstream outFile;\n\toutFile.open(path.c_str());\n\n\toutFile << \"{\\n  \\\"DLL\\\":{\\n\";\n\n\tbool first_DLL = true;\n\tfor (std::pair<std::string, struct IAT_DLL_entry> element : table)\n\t{\n\t\tif (!first_DLL) {\n\t\t\toutFile << \",\\n\";\n\t\t}\n\t\tfirst_DLL = false;\n\t\toutFile << \"    \\\"\" << element.first << \"\\\":{\\n\";\n\t\toutFile << \"      \\\"LoadLibrary_RVA\\\":\\\"\" << int_to_hex(element.second.LoadLibrary_addr) << \"\\\",\\n\";\n\t\toutFile << \"      \\\"functions\\\":{\\n\";\n\n\t\tbool first_function = true;\n\t\tfor (struct IAT_Func_entry entry : element.second.functions)\n\t\t{\n\t\t\tif (!first_function) {\n\t\t\t\toutFile << \",\\n\";\n\t\t\t}\n\t\t\tfirst_function = false;\n\t\t\toutFile << \"        \\\"\" << entry.Function_name << \"\\\":{\\n\";\n\t\t\toutFile << \"          \\\"IAT_RVA\\\":\\\"\" << int_to_hex(entry.IAT_RVA) <<\"\\\",\\n\";\n\t\t\toutFile << \"          \\\"GetProcAddress_RVA\\\":\\\"\" << int_to_hex(entry.GetProcAddress_addr) << \"\\\"\\n\";\n\t\t\toutFile << \"        }\";\n\t\t}\n\t\toutFile << \"\\n      }\\n\";\n\t\toutFile << \"    }\";\n\t}\n\toutFile << \"\\n  }\\n}\\n\";\n\n\toutFile.close();\n\tstd::cerr << \"IAT saved in \" << path << endl;\n}"
  },
  {
    "path": "pin-unpacker/IAT.h",
    "content": "#pragma once\n\n#include <iostream>\n#include <vector>\n\n#include \"pin.H\"\n\nstruct IAT_Func_entry {\n\tstd::string Function_name;\n\tADDRINT IAT_RVA;\n\tADDRINT GetProcAddress_addr;\n};\n\nstruct IAT_DLL_entry {\n\tADDRINT LoadLibrary_addr;\n\tstd::vector<struct IAT_Func_entry> functions;\n};\n\ntypedef std::map<std::string, struct IAT_DLL_entry> IAT_table;\n\nvoid IAT_add_library(IAT_table& table, char* DLL_Name, ADDRINT LoadLibrary_addr);\n\nvoid IAT_add_function(IAT_table& table, char* DLL_Name, char* function_name, ADDRINT function_addr, ADDRINT GetProcAddress_addr);\n\nvoid IAT_print(const IAT_table& table, std::ostream* out);\n\nvoid IAT_json_save(const IAT_table& table, const std::string& path);"
  },
  {
    "path": "pin-unpacker/IAT_repair.py",
    "content": "import argparse\nimport lief\nimport os\nimport json\n\ndef align(x, al):\n    \"\"\" return <x> aligned to <al> \"\"\"\n    if x % al == 0:\n        return x\n    else:\n        return x - (x % al) + al\n\n\ndef pad_data(data, al):\n    \"\"\" return <data> padded with 0 to a size aligned with <al> \"\"\"\n    return data + ([0] * (align(len(data), al) - len(data)))\n\n\nclass ImportTableBuilder:\n\n    def __init__(self, baseoffset, ptr_size):\n        self.data = b\"\"\n        self.hint_name_RVA_dict = {}\n        self.name_thunk_RVA_dict = {}\n        self.baseoffset = baseoffset\n        self.IDT_RVA = 0\n        self.ptr_size = ptr_size\n\n\n    def _add_name(self, name, hint=0):\n        self.hint_name_RVA_dict[name] = self.baseoffset + len(self.data)\n        self.data += b\"\\x00\\x00\" # hint field, added even for DLL names\n        self.data += name.encode(\"ASCII\") + b'\\x00'\n\n\n    def _add_thunk_list(self, dllname, name_list):\n        self.name_thunk_RVA_dict[dllname] = self.baseoffset + len(self.data)\n        for n in name_list:\n            self._push(self.hint_name_RVA_dict[n], self.ptr_size)\n        self._push(0, self.ptr_size) #end of the array\n\n\n    def _add_import_descriptor(self, dllname, IAT_RVA):\n        if(self.IDT_RVA ==0):\n            self.IDT_RVA = self.baseoffset + len(self.data)\n        self._push(self.name_thunk_RVA_dict[dllname], 4) #OriginalFirstThunk\n        self._push(0, 4) #TimeDateStamp\n        self._push(0, 4) #ForwarderChain\n        self._push(self.hint_name_RVA_dict[dllname] + 2, 4) #DLLname, + 2 to ignore hint field\n        self._push(IAT_RVA, 4) #FirstThunk\n\n\n    def _push(self, val, size):\n        self.data += val.to_bytes(size, \"little\")\n\n\n    def _init_IAT(self, input_PE, base_IAT_addr, name_list):\n        \"\"\"\n        Init the IAT to point to the functions names we created\n        \"\"\"\n        rva = base_IAT_addr\n        for n in name_list:\n            data = list(self.hint_name_RVA_dict[n].to_bytes(self.ptr_size, \"little\"))\n            input_PE.patch_address(rva, data, lief.Binary.VA_TYPES.RVA)\n            rva += self.ptr_size\n\n\n    def build(self, imports_names, IAT_locations, input_PE):\n        \"\"\"\n            import_names = {\n                'DLL_name':['functions_names']\n            }\n\n            IAT_locations = {'DLL_name':RVA}\n        \"\"\"\n\n        for dll_name, func_names_list in imports_names.items():\n            self._add_name(dll_name)  \n            for fun_name in func_names_list:\n                self._add_name(fun_name)\n\n            self._add_thunk_list(dll_name, func_names_list)\n            self._init_IAT(input_PE, IAT_locations[dll_name], func_names_list)\n\n        for dll_name in imports_names.keys():\n            self._add_import_descriptor(dll_name, IAT_locations[dll_name])\n        self._push(0, 20) # empty import_descriptor to finish the array\n\n\nif __name__ ==\"__main__\" :\n\n    parser = argparse.ArgumentParser(description='Pack PE binary')\n    parser.add_argument('input', metavar=\"FILE\", help='input PE file')\n    parser.add_argument('iat_file', metavar=\"IAT FILE\", help='input IAT json file')\n    parser.add_argument('-o', metavar=\"FILE\", help='output', default=\"IAT_corrected.exe\")\n\n    args = parser.parse_args()\n\n    with open(args.iat_file, \"r\") as f:\n        IAT_data = json.load(f)\n\n    input_PE = lief.PE.parse(args.input)\n\n    # get RVA for new section\n    max_RVA = max([x.virtual_address + x.size for x in input_PE.sections])\n    max_RVA = align(max_RVA, input_PE.optional_header.section_alignment)\n\n    import_names = {}\n    IAT_locations = {}\n\n    for dll_name in IAT_data[\"DLL\"].keys():\n        import_names[dll_name] = []\n        IAT_locations[dll_name] = 0\n\n        func_dict = IAT_data[\"DLL\"][dll_name][\"functions\"]\n\n        for fun_name in func_dict.keys():\n            import_names[dll_name] += [fun_name]\n\n        IAT_loc = min([int(infos[\"IAT_RVA\"], 16) for (name, infos) in func_dict.items()])\n\n        IAT_locations[dll_name] = IAT_loc\n\n    builder = ImportTableBuilder(max_RVA, 8)\n\n    builder.build(import_names, IAT_locations, input_PE)\n\n    import_data = pad_data(list(builder.data), input_PE.optional_header.file_alignment)\n    import_section = lief.PE.Section(name=\".imp\")\n    import_section.content = import_data\n    import_section.size = len(import_data)\n    import_section.virtual_address = max_RVA\n    import_section.characteristics = (lief.PE.SECTION_CHARACTERISTICS.MEM_READ\n                                        | lief.PE.SECTION_CHARACTERISTICS.MEM_WRITE)\n\n    input_PE.add_section(import_section)\n\n    # change the file ehaders\n\n    # make lief compute the new sizeof_image\n    input_PE.optional_header.sizeof_image = 0\n\n    # chagne the Import table to point to ours\n    import_data_dir = input_PE.data_directory(lief.PE.DATA_DIRECTORY.IMPORT_TABLE)\n    import_data_dir.rva = builder.IDT_RVA\n    import_data_dir.size = len(builder.data)\n\n    # not supposed to move (no reloctions table)\n    input_PE.optional_header.dll_characteristics = 0\n\n    # make all sections writable (make sur the IAT is writable)\n    for s in input_PE.sections:\n        s.characteristics = s.characteristics | lief.PE.SECTION_CHARACTERISTICS.MEM_WRITE\n\n\n    # save the resulting PE\n    if(os.path.exists(args.o)):\n        # little trick here : lief emits no warning when it cannot write because the output\n        # file is already opened. Using this function ensure we fail in this case (avoid errors).\n        os.remove(args.o)\n\n    builder = lief.PE.Builder(input_PE)\n    builder.build()\n    builder.write(args.o)\n\n    print(f\"Output saved in {args.o}\")\n\n\n\n\n\n"
  },
  {
    "path": "pin-unpacker/MyPinTool.vcxproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug|Win32\">\n      <Configuration>Debug</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug|x64\">\n      <Configuration>Debug</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|Win32\">\n      <Configuration>Release</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|x64\">\n      <Configuration>Release</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <ProjectGuid>{639EF517-FCFC-408E-9500-71F0DC0458DB}</ProjectGuid>\n    <RootNamespace>MyPinTool</RootNamespace>\n    <Keyword>Win32Proj</Keyword>\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\n    <ProjectName>Unpacker</ProjectName>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <CharacterSet>MultiByte</CharacterSet>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <CharacterSet>MultiByte</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n    <PreferredToolArchitecture>x86</PreferredToolArchitecture>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <CharacterSet>MultiByte</CharacterSet>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <CharacterSet>MultiByte</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <PropertyGroup>\n    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>\n    <OutDir Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">$(ProjectDir)$(Platform)\\$(Configuration)\\</OutDir>\n    <IntDir Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">$(Platform)\\$(Configuration)\\</IntDir>\n    <LinkIncremental Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">false</LinkIncremental>\n    <GenerateManifest Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">false</GenerateManifest>\n    <OutDir Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">$(ProjectDir)$(Platform)\\$(Configuration)\\</OutDir>\n    <IntDir Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">$(Platform)\\$(Configuration)\\</IntDir>\n    <LinkIncremental Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">false</LinkIncremental>\n    <GenerateManifest Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">false</GenerateManifest>\n    <OutDir Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">$(ProjectDir)$(Platform)\\$(Configuration)\\</OutDir>\n    <IntDir Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">$(Platform)\\$(Configuration)\\</IntDir>\n    <LinkIncremental Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">false</LinkIncremental>\n    <GenerateManifest Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">false</GenerateManifest>\n    <OutDir Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">$(ProjectDir)$(Platform)\\$(Configuration)\\</OutDir>\n    <IntDir Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">$(Platform)\\$(Configuration)\\</IntDir>\n    <LinkIncremental Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">false</LinkIncremental>\n    <GenerateManifest Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">false</GenerateManifest>\n    <CodeAnalysisRuleSet Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">AllRules.ruleset</CodeAnalysisRuleSet>\n    <CodeAnalysisRules Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" />\n    <CodeAnalysisRuleAssemblies Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" />\n    <CodeAnalysisRuleSet Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">AllRules.ruleset</CodeAnalysisRuleSet>\n    <CodeAnalysisRules Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" />\n    <CodeAnalysisRuleAssemblies Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" />\n    <CodeAnalysisRuleSet Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">AllRules.ruleset</CodeAnalysisRuleSet>\n    <CodeAnalysisRules Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" />\n    <CodeAnalysisRuleAssemblies Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" />\n    <CodeAnalysisRuleSet Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">AllRules.ruleset</CodeAnalysisRuleSet>\n    <CodeAnalysisRules Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" />\n    <CodeAnalysisRuleAssemblies Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" />\n  </PropertyGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <ClCompile>\n      <AdditionalOptions>/GR- /GS- /EHs- /EHa- /Oi- /FIinclude/msvc_compat.h %(AdditionalOptions)</AdditionalOptions>\n      <Optimization>Disabled</Optimization>\n      <AdditionalIncludeDirectories>$(PINTOOLS_DIR)\\source\\include\\pin;$(PINTOOLS_DIR)\\source\\include\\pin\\gen;$(PINTOOLS_DIR)\\source\\toolsInstLib;$(PINTOOLS_DIR)\\extras\\xed-ia32\\include\\xed;$(PINTOOLS_DIR)\\extras\\components\\include;$(PINTOOLS_DIR)\\extras\\stlport\\include;$(PINTOOLS_DIR)\\extras;$(PINTOOLS_DIR)\\extras\\libstdc++\\include;$(PINTOOLS_DIR)\\extras\\crt\\include;$(PINTOOLS_DIR)\\extras\\crt;$(PINTOOLS_DIR)\\extras\\crt\\include\\arch-x86;$(PINTOOLS_DIR)\\extras\\crt\\include\\kernel\\uapi;$(PINTOOLS_DIR)\\extras\\crt\\include\\kernel\\uapi\\asm-x86;%(AdditionalIncludeDirectories);$(WindowsSdkDir)\\include</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions>TARGET_IA32;HOST_IA32;TARGET_WINDOWS;__PIN__=1;PIN_CRT=1;__i386__;_WINDOWS_H_PATH_=$(WIN10SDK_INCLUDE)/um</PreprocessorDefinitions>\n      <MinimalRebuild>false</MinimalRebuild>\n      <ExceptionHandling>\n      </ExceptionHandling>\n      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\n      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\n      <BufferSecurityCheck>false</BufferSecurityCheck>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>\n      <RuntimeTypeInfo>false</RuntimeTypeInfo>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\n      <DisableSpecificWarnings>4530;5208;%(DisableSpecificWarnings)</DisableSpecificWarnings>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n      <LanguageStandard_C>stdc17</LanguageStandard_C>\n    </ClCompile>\n    <Link>\n      <AdditionalOptions>/export:main /ignore:4210 /ignore:4281 %(AdditionalOptions)</AdditionalOptions>\n      <AdditionalDependencies>pin.lib;xed.lib;pinvm.lib;pincrt.lib;ntdll-32.lib;kernel32.lib;crtbeginS.obj</AdditionalDependencies>\n      <AdditionalLibraryDirectories>$(PINTOOLS_DIR)\\ia32\\lib;$(PINTOOLS_DIR)\\ia32\\lib-ext;$(PINTOOLS_DIR)\\extras\\xed-ia32\\lib;$(PINTOOLS_DIR)\\ia32\\runtime\\pincrt;%(AdditionalLibraryDirectories);$(WindowsSdkDir)\\lib</AdditionalLibraryDirectories>\n      <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>\n      <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <SubSystem>NotSet</SubSystem>\n      <OptimizeReferences>false</OptimizeReferences>\n      <EntryPointSymbol>Ptrace_DllMainCRTStartup%4012</EntryPointSymbol>\n      <BaseAddress>0x55000000</BaseAddress>\n      <TargetMachine>MachineX86</TargetMachine>\n      <AllowIsolation>true</AllowIsolation>\n      <ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <Midl>\n      <TargetEnvironment>X64</TargetEnvironment>\n    </Midl>\n    <ClCompile>\n      <AdditionalOptions>/GR- /GS- /EHs- /EHa- /Oi- /FIinclude/msvc_compat.h %(AdditionalOptions)</AdditionalOptions>\n      <Optimization>Disabled</Optimization>\n      <AdditionalIncludeDirectories>$(PINTOOLS_DIR)\\source\\include\\pin;$(PINTOOLS_DIR)\\source\\include\\pin\\gen;$(PINTOOLS_DIR)\\source\\toolsInstLib;$(PINTOOLS_DIR)\\extras\\xed-intel64\\include\\xed;$(PINTOOLS_DIR)\\extras\\components\\include;$(PINTOOLS_DIR)\\extras\\stlport\\include;$(PINTOOLS_DIR)\\extras;$(PINTOOLS_DIR)\\extras\\libstdc++\\include;$(PINTOOLS_DIR)\\extras\\crt\\include;$(PINTOOLS_DIR)\\extras\\crt;$(PINTOOLS_DIR)\\extras\\crt\\include\\arch-x86_64;$(PINTOOLS_DIR)\\extras\\crt\\include\\kernel\\uapi;$(PINTOOLS_DIR)\\extras\\crt\\include\\kernel\\uapi\\asm-x86;$(WindowsSdkDir)\\include;%(AdditionalIncludeDirectories);$(WindowsSdkDir)\\include</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions>TARGET_IA32E;HOST_IA32E;TARGET_WINDOWS;__PIN__=1;PIN_CRT=1;__LP64__;_WINDOWS_H_PATH_=$(WIN10SDK_INCLUDE)/um</PreprocessorDefinitions>\n      <MinimalRebuild>false</MinimalRebuild>\n      <ExceptionHandling>\n      </ExceptionHandling>\n      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\n      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\n      <BufferSecurityCheck>false</BufferSecurityCheck>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <RuntimeTypeInfo>false</RuntimeTypeInfo>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\n      <DisableSpecificWarnings>4530;5208;%(DisableSpecificWarnings)</DisableSpecificWarnings>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n      <LanguageStandard_C>stdc17</LanguageStandard_C>\n    </ClCompile>\n    <Link>\n      <AdditionalOptions>/export:main /ignore:4210 /ignore:4281 %(AdditionalOptions)</AdditionalOptions>\n      <AdditionalDependencies>pin.lib;xed.lib;pinvm.lib;pincrt.lib;ntdll-64.lib;kernel32.lib;crtbeginS.obj</AdditionalDependencies>\n      <AdditionalLibraryDirectories>$(PINTOOLS_DIR)\\intel64\\lib;$(PINTOOLS_DIR)\\intel64\\lib-ext;$(PINTOOLS_DIR)\\extras\\xed-intel64\\lib;$(PINTOOLS_DIR)\\intel64\\runtime\\pincrt;$(WindowsSdkDir)\\lib;%(AdditionalLibraryDirectories);$(WindowsSdkDir)\\lib</AdditionalLibraryDirectories>\n      <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>\n      <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <SubSystem>NotSet</SubSystem>\n      <OptimizeReferences>false</OptimizeReferences>\n      <EntryPointSymbol>Ptrace_DllMainCRTStartup</EntryPointSymbol>\n      <BaseAddress>0xC5000000</BaseAddress>\n      <TargetMachine>MachineX64</TargetMachine>\n      <AllowIsolation>true</AllowIsolation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <ClCompile>\n      <AdditionalOptions>/GR- /GS- /EHs- /EHa- /Oi- /FIinclude/msvc_compat.h %(AdditionalOptions)</AdditionalOptions>\n      <IntrinsicFunctions>false</IntrinsicFunctions>\n      <WholeProgramOptimization>false</WholeProgramOptimization>\n      <AdditionalIncludeDirectories>$(PINTOOLS_DIR)\\source\\include\\pin;$(PINTOOLS_DIR)\\source\\include\\pin\\gen;$(PINTOOLS_DIR)\\source\\toolsInstLib;$(PINTOOLS_DIR)\\extras\\xed-ia32\\include\\xed;$(PINTOOLS_DIR)\\extras\\components\\include;$(PINTOOLS_DIR)\\extras\\stlport\\include;$(PINTOOLS_DIR)\\extras;$(PINTOOLS_DIR)\\extras\\libstdc++\\include;$(PINTOOLS_DIR)\\extras\\crt\\include;$(PINTOOLS_DIR)\\extras\\crt;$(PINTOOLS_DIR)\\extras\\crt\\include\\arch-x86;$(PINTOOLS_DIR)\\extras\\crt\\include\\kernel\\uapi;$(PINTOOLS_DIR)\\extras\\crt\\include\\kernel\\uapi\\asm-x86;%(AdditionalIncludeDirectories);$(WindowsSdkDir)\\include</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions>TARGET_IA32;HOST_IA32;TARGET_WINDOWS;__PIN__=1;PIN_CRT=1;__i386__;_WINDOWS_H_PATH_=$(WIN10SDK_INCLUDE)/um</PreprocessorDefinitions>\n      <MinimalRebuild>false</MinimalRebuild>\n      <ExceptionHandling>\n      </ExceptionHandling>\n      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\n      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\n      <BufferSecurityCheck>false</BufferSecurityCheck>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>\n      <RuntimeTypeInfo>false</RuntimeTypeInfo>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <DebugInformationFormat>\n      </DebugInformationFormat>\n      <DisableSpecificWarnings>4530;5208;%(DisableSpecificWarnings)</DisableSpecificWarnings>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n      <LanguageStandard_C>stdc17</LanguageStandard_C>\n    </ClCompile>\n    <Link>\n      <AdditionalOptions>/export:main /ignore:4210 /ignore:4281 %(AdditionalOptions)</AdditionalOptions>\n      <AdditionalDependencies>pin.lib;xed.lib;pinvm.lib;pincrt.lib;ntdll-32.lib;kernel32.lib;crtbeginS.obj</AdditionalDependencies>\n      <AdditionalLibraryDirectories>$(PINTOOLS_DIR)\\ia32\\lib;$(PINTOOLS_DIR)\\ia32\\lib-ext;$(PINTOOLS_DIR)\\extras\\xed-ia32\\lib;$(PINTOOLS_DIR)\\ia32\\runtime\\pincrt;%(AdditionalLibraryDirectories);$(WindowsSdkDir)\\lib</AdditionalLibraryDirectories>\n      <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>\n      <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <SubSystem>NotSet</SubSystem>\n      <OptimizeReferences>true</OptimizeReferences>\n      <EnableCOMDATFolding>\n      </EnableCOMDATFolding>\n      <LinkTimeCodeGeneration>\n      </LinkTimeCodeGeneration>\n      <EntryPointSymbol>Ptrace_DllMainCRTStartup%4012</EntryPointSymbol>\n      <BaseAddress>0x55000000</BaseAddress>\n      <TargetMachine>MachineX86</TargetMachine>\n      <ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <Midl>\n      <TargetEnvironment>X64</TargetEnvironment>\n    </Midl>\n    <ClCompile>\n      <AdditionalOptions>/GR- /GS- /EHs- /EHa- /Oi- /FIinclude/msvc_compat.h %(AdditionalOptions)</AdditionalOptions>\n      <IntrinsicFunctions>false</IntrinsicFunctions>\n      <WholeProgramOptimization>false</WholeProgramOptimization>\n      <AdditionalIncludeDirectories>$(PINTOOLS_DIR)\\source\\include\\pin;$(PINTOOLS_DIR)\\source\\include\\pin\\gen;$(PINTOOLS_DIR)\\source\\toolsInstLib;$(PINTOOLS_DIR)\\extras\\xed-intel64\\include\\xed;$(PINTOOLS_DIR)\\extras\\components\\include;$(PINTOOLS_DIR)\\extras\\stlport\\include;$(PINTOOLS_DIR)\\extras;$(PINTOOLS_DIR)\\extras\\libstdc++\\include;$(PINTOOLS_DIR)\\extras\\crt\\include;$(PINTOOLS_DIR)\\extras\\crt;$(PINTOOLS_DIR)\\extras\\crt\\include\\arch-x86_64;$(PINTOOLS_DIR)\\extras\\crt\\include\\kernel\\uapi;$(PINTOOLS_DIR)\\extras\\crt\\include\\kernel\\uapi\\asm-x86;$(WindowsSdkDir)\\include;%(AdditionalIncludeDirectories);$(WindowsSdkDir)\\include</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions>TARGET_IA32E;HOST_IA32E;TARGET_WINDOWS;__PIN__=1;PIN_CRT=1;__LP64__;_WINDOWS_H_PATH_=$(WIN10SDK_INCLUDE)/um</PreprocessorDefinitions>\n      <MinimalRebuild>false</MinimalRebuild>\n      <ExceptionHandling>\n      </ExceptionHandling>\n      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\n      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\n      <BufferSecurityCheck>false</BufferSecurityCheck>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <RuntimeTypeInfo>false</RuntimeTypeInfo>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <DebugInformationFormat>\n      </DebugInformationFormat>\n      <DisableSpecificWarnings>4530;5208;%(DisableSpecificWarnings)</DisableSpecificWarnings>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n      <LanguageStandard_C>stdc17</LanguageStandard_C>\n    </ClCompile>\n    <Link>\n      <AdditionalOptions>/export:main /ignore:4210 /ignore:4281 %(AdditionalOptions)</AdditionalOptions>\n      <AdditionalDependencies>pin.lib;xed.lib;pinvm.lib;pincrt.lib;ntdll-64.lib;kernel32.lib;crtbeginS.obj</AdditionalDependencies>\n      <AdditionalLibraryDirectories>$(PINTOOLS_DIR)\\intel64\\lib;$(PINTOOLS_DIR)\\intel64\\lib-ext;$(PINTOOLS_DIR)\\extras\\xed-intel64\\lib;$(PINTOOLS_DIR)\\intel64\\runtime\\pincrt;$(WindowsSdkDir)\\lib;%(AdditionalLibraryDirectories);$(WindowsSdkDir)\\lib</AdditionalLibraryDirectories>\n      <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>\n      <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <SubSystem>NotSet</SubSystem>\n      <OptimizeReferences>true</OptimizeReferences>\n      <EnableCOMDATFolding>\n      </EnableCOMDATFolding>\n      <LinkTimeCodeGeneration>\n      </LinkTimeCodeGeneration>\n      <EntryPointSymbol>Ptrace_DllMainCRTStartup</EntryPointSymbol>\n      <BaseAddress>0xC5000000</BaseAddress>\n      <TargetMachine>MachineX64</TargetMachine>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemGroup>\n    <ClCompile Include=\"export_pin.cpp\" />\n    <ClCompile Include=\"IAT.cpp\" />\n    <ClCompile Include=\"export_windows.cpp\" />\n    <ClCompile Include=\"pin_utils.cpp\" />\n    <ClCompile Include=\"utils.cpp\" />\n    <ClCompile Include=\"Upacker.cpp\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"export.h\" />\n    <ClInclude Include=\"pin_utils.h\" />\n    <ClInclude Include=\"utils.h\" />\n    <ClInclude Include=\"IAT.h\" />\n  </ItemGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n  </ImportGroup>\n</Project>"
  },
  {
    "path": "pin-unpacker/MyPinTool.vcxproj.user",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"Current\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup />\n</Project>"
  },
  {
    "path": "pin-unpacker/README.md",
    "content": "\n# Compilation configuration\n\n## Environment variables\n\n2 environment variables needed :\n\n  * `PINTOOL_DIR` : pintool installation, so folder `$(PINTOOL_DIR)/source/include/pin` exists\n  * `WIN10SDK_INCLUDE` : SDK installation dir, so `$(WIN10SDK_INCLUDE)/um/windows.h`  exists (should me something like `C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.19041.0`)\n\nAdd them through `sysdm.cpl` > Advanced > Envrionment Variables"
  },
  {
    "path": "pin-unpacker/Unpacker.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 16\nVisualStudioVersion = 16.0.31105.61\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"MyPinTool\", \"MyPinTool.vcxproj\", \"{639EF517-FCFC-408E-9500-71F0DC0458DB}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|x64 = Debug|x64\n\t\tDebug|x86 = Debug|x86\n\t\tRelease|x64 = Release|x64\n\t\tRelease|x86 = Release|x86\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x64.ActiveCfg = Debug|x64\n\t\t{639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x64.Build.0 = Debug|x64\n\t\t{639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x86.ActiveCfg = Debug|Win32\n\t\t{639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x86.Build.0 = Debug|Win32\n\t\t{639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x64.ActiveCfg = Release|x64\n\t\t{639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x64.Build.0 = Release|x64\n\t\t{639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x86.ActiveCfg = Release|Win32\n\t\t{639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x86.Build.0 = Release|Win32\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {2F8ECBE6-FF9D-4D3D-B2AB-EC87B9F25AAB}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "pin-unpacker/Upacker.cpp",
    "content": "#include <iostream>\n#include <fstream>\n#include <string.h>\n\n#include \"pin.H\"\n#include \"utils.h\" \n#include \"pin_utils.h\" \n#include \"IAT.h\"\n#include \"export.h\"\n\nusing std::endl;\n\nstd::ostream * out = &std::cerr;\n\n/*\n    GLOBAL VARIABLES\n*/\n\nIAT_table iat_table;\nchar* last_LoadLibrary = NULL;\n\nVOID save_results(ADDRINT OEP) {\n    //IAT_print(iat_table, out);\n    export_image(get_main_IMG(), OEP, \"export.exe\");\n    IAT_json_save(iat_table, \"IAT.json\");\n\n    exit(0); //FIXME better solution ? continue and do multiple exports (TLS) ?\n}\n\nVOID Fini(INT32 code, VOID *v)\n{\n    IAT_print(iat_table, out);\n    *out << \"DONE\" << std::endl;\n}\n\n/*  Finds a function RTN object\n    RTN must be closed after use\n*/\nRTN FindRoutine(IMG image, std::string name) {\n    for (SYM sym = IMG_RegsymHead(image); SYM_Valid(sym); sym = SYM_Next(sym))\n    {\n        std::string fname = PIN_UndecorateSymbolName(SYM_Name(sym), UNDECORATION_NAME_ONLY);\n        if (fname == name)\n        {\n            RTN rtn = RTN_FindByAddress(IMG_LowAddress(image) + SYM_Value(sym));\n            if (RTN_Valid(rtn))\n            {\n                return rtn;\n            }\n        }\n    }\n    return RTN_Invalid();\n}\n\nVOID Callback_LoadLibrary(const CONTEXT* ctx, char* lib_name)\n{\n    ADDRINT saved_EIP = get_stack(ctx, 0);\n    if (in_main_module(saved_EIP))\n    {\n       // *out << \"Callback : LoadLibrary(\" << lib_name << \") @ \" << int_to_hex(saved_EIP) << endl;\n        last_LoadLibrary = lib_name;\n        IAT_add_library(iat_table, lib_name, get_RVA(saved_EIP));\n    }\n}\n\nVOID Callback_GetProcAddress(const CONTEXT* ctx, char* funct_name)\n{\n    ADDRINT RBX = (ADDRINT)PIN_GetContextReg(ctx, REG_RBX);\n    ADDRINT saved_EIP = get_stack(ctx, 0);\n    if (in_main_module(saved_EIP))\n    {\n        //*out << \"Callback : GetProcAddress(\" << last_LoadLibrary << \", \" << funct_name << \") @ \" << int_to_hex(saved_EIP) << endl;\n        //*out << \"    RBX=\" << int_to_hex(RBX) << \" (\" << int_to_hex(get_RVA(RBX)) << \")\" << endl;\n        IAT_add_function(iat_table, last_LoadLibrary, funct_name, get_RVA(RBX), get_RVA(saved_EIP)); //FIXME\n    }\n}\n\n/* Called on DLL loaded by the Application */\nVOID Callback_ImageLoad(IMG image, VOID* v)\n{\n    //*out << \"Loading \" << IMG_Name(image) << endl;\n    RTN funct_rtn = FindRoutine(image, \"LoadLibraryA\");\n    if (RTN_Valid(funct_rtn))\n    {\n        //*out << \"Instrumenting LoadLibraryA in \" << IMG_Name(image) << endl;\n        RTN_Open(funct_rtn);\n        RTN_InsertCall(funct_rtn, IPOINT_BEFORE, (AFUNPTR)Callback_LoadLibrary, IARG_CONTEXT, IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END);\n        RTN_Close(funct_rtn);\n    }\n\n    funct_rtn = FindRoutine(image, \"GetProcAddress\");\n    if (RTN_Valid(funct_rtn))\n    {\n        //*out << \"Instrumenting GetProcAddress in \" << IMG_Name(image) << endl;\n        RTN_Open(funct_rtn);\n        RTN_InsertCall(funct_rtn, IPOINT_BEFORE, (AFUNPTR)Callback_GetProcAddress, IARG_CONTEXT, IARG_FUNCARG_ENTRYPOINT_VALUE, 1, IARG_END);\n        RTN_Close(funct_rtn);\n    }\n}\n\nADDRINT main_exec_section = 0;\nbool last_in_exec_section = true;\nADDRINT last_ins = 0;\n\nVOID Callback_Instruction(INS ins, VOID*) {\n    // check instruction in main module\n    ADDRINT ins_addr = INS_Address(ins);\n\n    if (in_main_module(ins_addr)) { //FIXME : VirtualAlloc ?\n        SEC ins_sec = Find_Section(ins_addr);\n        if (!SEC_Valid(ins_sec)) {\n            // should never happen inside a module !\n            *out << \"ERROR : instruction in main module, but not in a section ? (\" << int_to_hex(ins_addr) << \")\" << endl;\n        }\n        else {\n            ADDRINT ins_secaddr = SEC_Address(ins_sec);\n            if (main_exec_section == 0) {\n                main_exec_section = ins_secaddr; //base section address for EntryPoint\n            }\n            else{\n                if (main_exec_section != ins_secaddr) {\n                    if (last_in_exec_section) {\n                        *out << \"Inter section jump found : RVA \" << int_to_hex(get_RVA(ins_addr)) << \" called from RVA \" << int_to_hex(get_RVA(last_ins)) << endl;\n                        save_results(ins_addr);\n                    }\n                    last_in_exec_section = false;\n                }\n                else {\n                    last_in_exec_section = true;\n                }\n            }\n        }\n    }\n\n    last_ins = ins_addr;\n}\n\nVOID Callback_AppStart(void* )\n{\n    //*out << \"AppStart callback\\n\";\n}\n\nint main(int argc, char *argv[])\n{\n    // Initialize PIN library. Print help message if -h(elp) is specified\n    // in the command line or the command line is invalid \n    if( PIN_Init(argc,argv) )\n    {\n        return 0;\n    }\n\n    PIN_InitSymbols();\n\n    IMG_AddInstrumentFunction(Callback_ImageLoad, NULL);\n    INS_AddInstrumentFunction(Callback_Instruction, NULL);\n\n    PIN_AddApplicationStartFunction(Callback_AppStart, NULL);\n    PIN_AddFiniFunction(Fini, NULL);\n  \n    // Start the program, never returns\n    PIN_StartProgram();\n    \n    return 0;\n}"
  },
  {
    "path": "pin-unpacker/export.h",
    "content": "#pragma once\n\n#include <iostream>\n#include \"pin.H\"\n\nvoid export_image(IMG img, ADDRINT OEP, const std::string& path);\n\nvoid export_image_buffer(void* data, size_t size, void* ImageBase, void* RVA_OEP, const std::string& path);\n\n"
  },
  {
    "path": "pin-unpacker/export_pin.cpp",
    "content": "/*\n\tPin side for the exports\n\twindows.h and pin.H cannot be included simultaneously\n*/\n\n#include <iostream>\n#include <string>\n\n#include \"pin.H\"\n\n#include \"export.h\"\n#include \"utils.h\"\n\nusing std::endl;\n\nvoid export_image(IMG img, ADDRINT OEP, const std::string& path) {\n\tsize_t size = IMG_HighAddress(img) - IMG_LowAddress(img) + 1;\n\tchar* buffer = (char*) malloc(size);\n\n\tPIN_SafeCopy(buffer, (void*) IMG_LowAddress(img), size);\n\n\texport_image_buffer(buffer, size, (void*)IMG_LowAddress(img), (void*) (OEP - IMG_LowAddress(img)), path);\n\n\tfree(buffer);\n\n\tstd::cerr << \"Module \" << IMG_Name(img) << \" saved at \" << path << endl;\n}"
  },
  {
    "path": "pin-unpacker/export_windows.cpp",
    "content": "/*\n\tFunctions of export.h that needs Windows.h included\n\twindows.h and pin.H cannot be included simultaneously\n*/\n\n#include <iostream>\n#include <string>\n\n#include <windows.h>\n#include <winnt.h>\n\n\n//#include \"export.h\" // this one includes pin, do NOT IMPORT\n#include \"utils.h\"\n\nusing std::endl;\n\nsize_t pad_size(size_t data, size_t align)\n{\n\tif (data % align == 0) {\n\t\treturn 0;\n\t}\n\telse {\n\t\treturn align - (data % align);\n\t}\n}\n\nsize_t align(size_t data, size_t align)\n{\n\treturn data + pad_size(data, align);\n}\n\n/*\n\tSaves the sections of a IMG object to a file\n*/\nvoid export_image_buffer(void* data, size_t size, void* ImageBase, void* RVA_OEP, const std::string& path)\n{\n\tIMAGE_DOS_HEADER* p_DOS_HDR = (IMAGE_DOS_HEADER*) data;\n\tIMAGE_NT_HEADERS* p_NT_HDR = (IMAGE_NT_HEADERS*)(((char*)p_DOS_HDR) + p_DOS_HDR->e_lfanew);\n\tIMAGE_SECTION_HEADER* sections = (IMAGE_SECTION_HEADER*)(p_NT_HDR + 1);\n\t\n\t//Change Optional Header, disable int size warnings\n\t#pragma warning(suppress: 4311)\n\t#pragma warning(suppress: 4302)\n\tp_NT_HDR->OptionalHeader.ImageBase = (ULONGLONG) ImageBase; // #FIXME : 64 bits ....\n\t\n\t#pragma warning(suppress: 4311)\n\t#pragma warning(suppress: 4302)\n\tp_NT_HDR->OptionalHeader.AddressOfEntryPoint = (DWORD) RVA_OEP;\n\n\t//Change sections :\n\t//\tall sections have RawSize = VirtualSize\n\t//  and RawAddress = VirtualAddress\n\n\tfor (int i = 0; i < p_NT_HDR->FileHeader.NumberOfSections; ++i) {\n\t\tsections[i].SizeOfRawData = sections[i].Misc.VirtualSize;\n\t\tsections[i].PointerToRawData = sections[i].VirtualAddress;\n\t}\n\n\t// Save the result\n\n\tFILE* file = fopen(path.c_str(), \"wb\");\n\tif (!file) {\n\t\tstd::cerr << \"ERROR opening output file \" << int_to_hex(GetLastError()) << endl;\n\t\treturn;\n\t}\n\n\tfwrite(data, size, 1, file);\n\n\tfclose(file);\n}"
  },
  {
    "path": "pin-unpacker/pin_utils.cpp",
    "content": "#include <iostream>\n\n#include \"pin_utils.h\"\n#include \"utils.h\"\n\nusing std::endl;\n\nSEC Find_Section(ADDRINT addr)\n{\n    //List images loaded in memory\n    IMG img = IMG_FindByAddress(addr);\n    if (IMG_Valid(img))\n    {\n        for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))\n        {\n            ADDRINT sec_addr = SEC_Address(sec);\n            USIZE sec_size = SEC_Size(sec);\n            if (addr >= sec_addr && addr <= sec_addr + sec_size)\n            {\n                return sec;\n            }\n        }\n    }\n    return SEC_Invalid();\n}\n\nbool in_main_module(ADDRINT addr)\n{\n    PIN_LockClient();\n    IMG img = IMG_FindByAddress(addr);\n    PIN_UnlockClient();\n\n    if (!IMG_Valid(img))\n    {\n        return false;\n    }\n    return IMG_IsMainExecutable(img);\n}\n\nADDRINT get_RVA(ADDRINT addr)\n{\n    PIN_LockClient();\n    IMG img = IMG_FindByAddress(addr);\n    PIN_UnlockClient();\n\n    if (!IMG_Valid(img))\n    {\n        std::cerr << \"WARNING : No module found for address \" << int_to_hex(addr) << endl;\n        return addr;\n    }\n    return addr - IMG_LowAddress(img);\n}\n\nADDRINT get_stack(const CONTEXT* ctx, ADDRINT offset)\n{\n    ADDRINT RSP = (ADDRINT)PIN_GetContextReg(ctx, REG_STACK_PTR);\n    ADDRINT data;\n    PIN_SafeCopy(&data, (void*)(RSP + offset), sizeof(ADDRINT));\n    return data;\n}\n\nvoid print_call_stack(const CONTEXT* ctx, std::ostream* out) {\n    ADDRINT RBP = (ADDRINT)PIN_GetContextReg(ctx, REG_RBP);\n    ADDRINT EIP_saved;\n    while (RBP != 0) {\n        PIN_SafeCopy(&EIP_saved, (void*)(RBP + sizeof(ADDRINT)), sizeof(ADDRINT));\n        *out << \" \" << int_to_hex(EIP_saved) << endl;\n        PIN_SafeCopy(&RBP, (void*)(RBP), sizeof(ADDRINT));\n    }\n}\n\nstatic IMG _main_img = IMG_Invalid();\n\nIMG get_main_IMG()\n{\n    if (IMG_Valid(_main_img)) {\n        return _main_img;\n    }\n    else {\n        for (IMG img = APP_ImgHead(); IMG_Valid(img); img = IMG_Next(img)) {\n            if (IMG_IsMainExecutable(img)) {\n                _main_img = img;\n                return _main_img;\n            }\n        }\n    }\n    return IMG_Invalid();\n\n}"
  },
  {
    "path": "pin-unpacker/pin_utils.h",
    "content": "#pragma once\n\n#include \"pin.H\"\n\nSEC Find_Section(ADDRINT addr);\nbool in_main_module(ADDRINT addr);\nADDRINT get_RVA(ADDRINT addr);\n\nADDRINT get_stack(const CONTEXT* ctx, ADDRINT offset);\n\nIMG get_main_IMG();"
  },
  {
    "path": "pin-unpacker/utils.cpp",
    "content": "#include <iostream>\n#include <strings.h>\n\nusing std::endl;\n\nstd::string int_to_hex(ADDRINT val)\n{\n    char buff[33];\n    sprintf(buff, \"0x%llx\", val);\n    return std::string(buff);\n}\n"
  },
  {
    "path": "pin-unpacker/utils.h",
    "content": "#pragma once\n\n#include <iostream>\n#include <string>\n\nstd::string int_to_hex(unsigned long long int val);\n"
  }
]