How to unpack exe

How to unpack exe

ResourcesExtract — утилита для распаковки файлов EXE, DLL, OCX и CPL

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

И сполняемые файлы EXE и DLL по своей сути являются архивами или лучше сказать контейнерами, способными хранить в себе различные типы данных, а не только один программный код. В свою очередь это означает, что подобно другим архивам файлы EXE также могут быть распакованы. Правда, обычные архиваторы здесь не помогут, для распаковки этого типа контейнеров нужны специальные утилиты, например, такие как ResourcesExtract.

Эта маленькая, легкая и очень простая утилита прекрасно справляется с распаковкой файлов. В отличие от профессиональных редакторов ресурсов, обычно используемых программистами и позволяющих «вытаскивать» их исполняемых файлов элементы по отдельности, ResourcesExtract работает как примерно так же как обычный архиватор. Она автоматически перебирает файлы в специальной папке, после чего извлекает данные в указанном пользователем месте.

Программа имеет простой и удобный пользовательский интерфейс, представленный одним единственным окном. Установки экстрактор не требует и может запускаться с любого переносного носителя. Утилита позволяет извлекать иконки, статические и анимированные курсоры, видео в AVI формате, файлы карт, манифестов, документы HTML и некоторые другие типы файлов. Что именно должна искать утилита, можно указать непосредственно в рабочем окне.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Из дополнительных возможностей приложения стоит упомянуть обработку вложенных директорий (глубина поиска указывается отдельно), конвертирование файлов карт в формат PNG, перезапись исходных элементов. Чтобы распаковать файл, нужно указать к нему путь, задать директорию для сохранения результатов и нажать кнопку старта. После того как элементы будут извлечены, утилита автоматически откроет содержащую их папку.

Опытные пользователи могут запускать приложение в режиме командной строки, выполнять пакетное сканирование файлов. В целом со своей работой данный экстрактор справляется неплохо, в то же время ResourcesExtract несколько уступает Universal Extractor — другой популярной программе для распаковки контейнеров. Распространяется ResourcesExtract бесплатно, рекламы программа не содержит, совместима с ОС Windows 7, 8 и 8.1. Язык интерфейса — английский.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Главная → FAQ → Как открыть exe файл архиватором

«.exe» — самый распространенный формат для установки программного обеспечения на пользовательский персональный компьютер. Также данный формат используется при создании самораспаковывающегося архивного файла в архиваторах WinRAR или 7 Zip.

«EXE» расширение – это сокращение слова «executable» с английского языка.

Google Translate: Executable – исполнимый, выполняемый, выполнимый, исполнимый

Получив такого рода файл, пользователь рискует получить неприятный сюрприз в виде вируса, вредоносного или шпионского ПО, даже если этот файл скачан с надёжного и проверенного источника. Именно поэтому многие квалифицированные специалисты рекомендуют предварительно просматривать содержимое файлов с разрешением «.exe» перед запуском/ инсталляцией. Иным причинам тоже может быть место в необходимости открытия файла в формате «.exe». Это могут быть разного рода причины: просмотр содержимого для достоверности в правильном получении, внесение изменений в состав архивного файла, извлечение только необходимых объектов и так далее.

Как открыть exe файл архиватором

Для открытия и предварительного просмотра содержимого архивного файла в формате «.exe», а не извлечения содержимого или начала установки той или иной программы, рекомендуется использовать самые популярные программы-архиваторы WinRAR или 7 Zip. Оба продукта достойны звания самых популярных программных обеспечений среди всех своих аналогов.

Чтобы именно открыть файл для просмотра, а не запуска, необходимо выбрать в диалоговом окне правильную функцию. Например, в архиваторе ВинРАР, нажав правой кнопкой мыши на исполняемом файле, надо выбрать не «Открыть»,

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

а опцию «открыть с помощью WinRAR».

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Теперь можно безопасно просмотреть содержимое, добавить или удалить определённый файл, либо извлечь только интересующий объект.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

В случае, когда пользователь интересуется непосредственно самим исполняемым кодом программы, можно воспользоваться сторонним опциональным специфическим инструментом. Во всемирной паутине можно найти и скачать множество таких утилит. В списке искомого могут быть:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Visual Studio от компании Microsoft с функционалом редактора исходного кода с технологией IntelliSense и элементарного перепроектирования кода.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Restorator — продукт от компании «Bome», для возможности редактировать файлы ресурсов.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

ResHacker сокращение от Resource Hacker – этопрограмма-редактор, с помощью которой можно просматривать, извлекать и менять ресурсы в исполнимых файлах «EXE» для 32/64 битных версий Microsoft Windows OS.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

ExeScope – утилита для предварительного просмотра и анализа содержимого файлов в формате «EXE», а также для возможности редактирования данных файлов.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Скачав и установив на своём персональном компьютере бесплатный архиватор 7-Zip или условно-бесплатный WinRAR, пользователь сможет решить поставленную перед ним задачу. Но не все файлы с разрешением «.exe» могут быть открыты для просмотра и редактирования содержимого. Поэтому не стоит останавливать свой выбор только на одном продукте. Для полноценной работы рекомендуется иметь целый арсенал разнофункциональных инструментариев.

Благо, благодаря многим энтузиастам практически любое программное обеспечение можно найти в сети абсолютно бесплатно, либо оно будет стоить символических денежных затрат. Большинство разработчиков предлагают своим пользователям демонстративный триальный период для свободного тестирования своего продукта. Интернет и мощный браузер вам в помощь, дорогие пользователи!

Распаковка исполняемых файлов

Привет, хабровчане. В рамках курса «Reverse-Engineering. Basic» Александр Колесников (специалист по комплексной защите объектов информатизации) подготовил авторскую статью.

Также приглашаем всех желающих на открытый вебинар по теме «Эксплуатация уязвимостей в драйвере. Часть 1». Участники вебинара вместе с экспертом разберут уязвимости переполнения в драйверах и особенности разработки эксплойтов в режиме ядра.

Статья расскажет о подходах к анализу запакованных исполняемых файлов с помощью простых средств для обратной разработки. Будут рассмотрены некоторые пакеры, которые применяются для упаковки исполняемых файлов. Все примеры будут проведены в ОС Windows, однако изучаемые подходы можно легко портировать на любую ОС.

Инструментарий и настройка ОС

Для тестов будем использовать виртуальную машину под управлением ОС Windows. Инструментарий будет содержать следующие приложения:

установленный по умолчанию плагин x64dbg Scylla;

Самый быстрый и простой способ провести распаковку любого исполняемого файла — применить отладчик. Но так как мы будем также рассматривать язык программирования Python, то может понадобится проект:

uncompile6 проект, который позволяет разобрать байткод виртуальной машины Python;

pyinstallerExtractor инструмент для распаковки архива pyInstaller.

Общие методы снятия паковки

Разберемся, что же такое паковка. В большинстве случаев исполняемые файлы современных языков программирования имеют довольно большой размер при минимальном наборе функций. Чтобы оптимизировать данную величину, можно применить паковку или сжатие. Наиболее распространенный на сегодняшний день пакер — UPX. Ниже приведен пример того, как пакер проводит сжатие исполняемого файла.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

На картинке может показаться, что файл стал по размеру больше, однако это не всегда так. Большинство файлов за счет такой модификации могут уменьшить свой размер до 1.5 раз от исходного объема.

Что же от этого реверс-инженеру? Почему надо знать и уметь определять, что файл упакован? Приведу наглядный пример. Ниже приведен снимок файла, который не запакован:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

И файл, который был пропущен через алгоритм UPX:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Изменения коснулись в этом случае двух основных точек исполняемого файла:

Точка входа — в случае с упакованным файлом это начало алгоритма распаковки, настоящий алгоритм программы будет работать только после того, как будет распакован оригинальный файл;

Код оригинального файла: теперь не найти паттернов, которые можно сразу разбирать как команды.

Итак, чтобы снова анализировать оригинальный файл, нужно найти настоящую или оригинальную точку входа. Для этого нужно разбить алгоритм на основные этапы:

Этап подготовки исполнения файла — загрузчик ОС настраивает окружение, загружает файл в оперативную память;

Сохранение контекста — упаковщик сохраняет контекст исполнения файла (набор значений регистров общего назначения, которые были установлены загрузчиком ОС);

Распаковка оригинального файла;

Передача управления оригинальному файлу.

Пример UPX

Попробуем с помощью отладчика найти оригинальную точку входа для приложения. Запечатлим оригинальную точку входа до упаковки UPX:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Как та же точка входа выглядит после упаковки:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Запустим отладчик и попробуем найти место сохранения контекста:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Ждем первого использования ESP — в отладчике при этом значение регистра подсветится красным цветом. Затем устанавливаем точку останова на адрес и просто запускаем приложение:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

В результате попадаем на оригинальную точку входа:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Вот так просто, теперь используя плагин Scylla Hide можно сохранить результирующий файл на жесткий диск и продолжить его анализ.

Подобный метод можно применять для любого упаковщика, который сохраняет контекст на стек.

Пример PyInstaller

Не всегда подобный подход работает для приложений, которые используют более сложную структуру исполняемого файла. Рассмотрим файл, который был создан с помощью PyInstaller — пакет, который позволяет преобразовать Python скрипт в исполняемый файл. При генерации исполняемого файла создается архив, который содержит виртуальную машину Python и все необходимые библиотеки. Сам исходный код приложения при этом преобразуется в байт код и его нельзя дезассемблировать.

Попробуем все же получить что-то читаемое. Создадим простое приложение на Python и упакуем с помощью PyInstaller. Исходный код приложения:

Установим пакет pyInstaller и создадим exe файл:

Итак, проведем сбор информации о том, что в итоге получилось. У нас есть архив, который должен запустить виртуальную машину, и код, который мы записали в виде скрипта. Попробуем восстановить исходник и просто его прочесть даже без запуска.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Таким образом можно снова получить исходный код.

Смотреть открытый вебинар по теме «Эксплуатация уязвимостей в драйвере. Часть 1».

Unpacking, reversing, patching

This article is an introduction of packing, how to unpack, to reverse an exe and finally patching it. I have chosen to show reversing of a sample exe file and how to patch it.

Packing/ Unpacking

Packing is the process of compressing an exe,including the data and decompressing function with the compressed exe itself [Fig-1].

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Unpacking is the reverse of this; it’s a process of identifying the decompressing function and extracts the original data out of exe.

Goals of packing:

There are lots of packers available such as UPX, NeoLite, PECompact, etc… to achieve the goals mentioned above.

Identifying the packer:

First, we need to identify the exe if it’s a packed executable file. To confirm this we will use a tool called PEiD, which can really tell us if this is packed and if yes, using what packer. Launch the PEiD tool and locate the executable. You will see it displaying the information based on which tool it was packed with. [Fig-2].

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Unpacking the exe:

We’ll use OllyDbg for unpacking the executable. Load the exe in OllyDbg; now there are two things in this exe, first- EP, which is the entry point where the OllyDbg lands; second is OEP, Original Entry Point, which is entry point for original code. So we have to detect the OEP in order to unpack the executable. As soon as the packed exe is loaded, it hit it’s EP [Fig-3].

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Once the EP is found, we need to look for the OEP, which is original entry point for the exe. We need to just keep scrolling until we find an instruction called POPAD, which is used to pop words into general purpose registers. Soon after POPAD, we need to find a jump instruction, which takes us to the OEP. Make a breakpoint at this address (POPAD). Press F9 to load and execute the packed exe which comes and pause at the breakpoint. As shown in the Fig-4, the OEP address is in jump instruction.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

OllyDump plugin:

OllyDump is a plugin (.dll) which dumps the active process to an executable file (PE). Now, press F8 until it takes the jump and reaches to the address (00401000). Once there, we will use OllyDump to dump the original code. Go to Plugins->OllyDump->Dump debugged process. We will be presented with the screen shown below in Fig-5. As we can see, the Entry point was the address of the packed executable which is being modified to a new address and being assigned to the EIP register for executing the next instruction.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Click the Dump button, save the new executable, which is now unpacked, to the location of your choice. Now the unpacked executable will be un-obfuscated, easy to read and analyze [Fig-6].

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Reverse engineering

Once the exe is unpacked, we will try to analyze it and patch it. As per Wikipedia, “Reverse engineering is the process of discovering the technological principles of a device, object, or system through analysis of its structure, function, and operation.” A source code is compiled to the object file and finally it’s linked to the executable. The executables are purely in binary mode and not in a human friendly form – it’s not human readable. So when we try to reverse the same process and bring back the executables to its object phase, which is called disassembling, it’s called reverse engineering. [Fig-7]

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Loading the exe to OllyDbg:

OllyDbg has four windows: Code Window-which shows assembly code of the application loaded, Register Window-shows values on each of the register, Stack Window-which shows different values loaded onto the stack at the time of execution and the Memory Dump Window. For executing instructions step by step, the F8 key is used; to run the application continuously F9 key is pressed. The F7 key is used to peek into any function and F2 is used to set a breakpoint where an application may be paused to check its behavior. There are several other options as well, but mainly only these four are used for the inspection of codes. [Fig-8]

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Reversing Exe

We shall start the reversing by using our unpacked exe (Crackme2.exe) [http://crackmes.de/ ]. Load the exe by going to the File menu of Olly and open the exe by locating it on your hard disk and the exe appears on the screen (Fig-9). As soon as the exe is loaded into Olly you can see a lot of assembly codes that is dissembled in the code section. To get a feel of the exe and what it does, press F9 to run it; the CrackMe.exe then appears on the screen:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

If you enter the wrong password and press OK, it will display a message “No luck there mate!” Since we don’t know the correct password, we can’t get through the application. So our goal will be to inspect the code and break this barrier to get the “Congrats…” message. This can be done in two ways:

The first option is a bit difficult as you really need to dive in each and every routine/subroutine and understand the logic. The second one is a bit easier as you only need to directly go and see how we can go to the logical end, and can then change the flow. We’ll carefully go through the assembly, understand the logic behind this and try to overcome the password checking. Again, there may lots of ways to break this functionality and that depends on the software’s behavior, but the ultimate goal is to bypass the password check. How and which routines/functions we need to inspect is entirely one’s personal way of doing that based on intuition, but more or less it will be similar approach. This is my way of doing that and it may differ with the method of others.

Now let’s understand the flow:

Now again, press CTRL+F2, this will reload the CrackMe2.exe into Olly (Fig-10). Once loaded, press F8 and step through the instructions to get an idea about the code. Olly lands at the following instructions:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

There are several APIs that are executed by them, such as, GetModuleHandleA, it returns the handle to the file of the current process. Similarly, few more APIs- FindWindowA, LoadIconA, LoadCursorA and CreateWindowExA which pretty much indicate that the exe being loaded and the icons and windows are being created. Similarly, ShowWindow and UpdateWindow are used to display a dialog box. But basically, what are we looking for is the API which actually takes the user input. Carefully going through the code window gives one API which seems to be a bit interesting: GetDlgItemTextA. We need to observe this very carefully because it’s where we give the input and will capture the logic. We need to put a breakpoint, which pauses the execution there, for further inspection. So we press F2 to set the breakpoint where the function starts at 004012B3 (in Red) [Fig-11]:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Now time to rerun the exe and catch at the breakpoint. Press CTRL+F2 to reload the app. Press F9 to run it, it will automatically come and halt at the set breakpoint. Now enter the password in the dialog box, I shall enter a two letter sample password ‘ni’ in the dialog box. As soon as we click ‘OK’, the execution halts at the breakpoint. Now it’s is for the real observation of the code. Press F8 to step through each following instruction. Everything seems pretty normal as the code just accepts the input and traverse internally to some other address not directly related to main flow. I just keep pressing until it again return back to main execution flow. Where I can see the strings entered by me is being pushed (PUSH CRACKME2.0040217E) [Fig-12]. Just after pushing, two functions are being called. We will examine them one by one.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Let’s examine Function1 at (CRACKME2.00401365). I press F7 to enter into the function [Fig-13]. The value (‘ni’) copied and being pushed using ESI. Now the instruction MOV AL,BYTE PTR DS:[ESI], taking the first letter ‘n’ from the value and copying to AL. Now AL is ‘n’ (6E), so TEST AL,AL is not zero (equivalent to cmp AL, 0), the jump is not taken and goes to next instruction INC BYTE PTR DS:[402118], which is for incrementing the counter. The next instruction CMP AL,41 compares ‘n’ (6E) with 41 (A). The flow goes to CMP AL, 5A and compares ‘n’ (6E) with 5A (Z), which probably checks if the value supplied is between A and Z. Since yes, the flow goes to CALL CRACKME2.004013B2, which is another subroutine.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Carefully inspecting the code, it shows that it just converting lower case letters to upper case (SUB AL, 20) [Fig-14].

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

The same instructions are repeated until the next letter ‘i’ is converted to ‘I’. Now the control goes to address 00401399 [Fig-15]. The instruction MOV CL,BYTE PTR DS:[EDI+4021A3] picks up one character, starting at 004021A3 from Hex dump and moving to CL (‘M’). The instruction MOV BL,BYTE PTR DS:[ESI] transfers one byte to BL (our password’s first letter ‘N’). XOR BL,CL does an XOR operation with ‘M’ and ‘N’. And it keeps doing that till our passwords last letter (‘I’) is finished. So, it has given us the hint that our password supplied is being XORed with the string at address 004021A3 (Messing_in_bytes), which is of 16 characters long. So that means our password length also should be 16. After XORing, the result is being pushed at address 0040217E [Fig-12]. In next call, CALL CRACKME2.004013B8, the result is being compared with the correct XOR result in 004013B8 [Function 2]. Now let’s examine this function [Function 2]. Press F7 to step in [Fig-16]. So, the string being returned from 004013B8 is starting from the address 00402150 ie, 1F 2C 37 36 3B 3D 28 19 3D 26 1A 31 2D 3B 37 3E.

So, now to get the original password, we need to XOR the Hex of ‘Messing_in_bytes’ and 1F 2C 37 36 3B 3D 28 19 3D 26 1A 31 2D 3B 37 3E

So, 4D 65 73 73 69 6E 67 5F 69 6E 5F 62 79 74 65 73 XOR 1F 2C 37 36 3B 3D 28 19 3D 26 1A 31 2D 3B 37 3E = 52 49 44 45 52 53 4F 46 54 48 45 53 54 4F 52 4D (nice calculator here http://www.jdejong.net/tools/bitwisecalculator.php )

Now convert above Hex string (52 49 44 45 52 53 4F 46 54 48 45 53 54 4F 52 4D) to ASCII, which gives:

“RIDERSOFTHESTORM”. So this is the correct password! So, if we feed this password in the Crackme2, we will get the message “Great work…”

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Patching the code

Highlight the CALL Crackme2.00401349 instruction, hit the SPACE bar on the keyboard and change the address to 00401334 then click Assemble (Figure-18). Now the code CALL Crackme2.00401349 gets replaced by CALL Crackme2.00401334.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

To save this patched code, right click in code window, select copy to executables, all modifications, Copy All, Save File as PatchedCrackme.exe

Rerun the patched exe and supply any random password and be greeted with “Good work mate…

Mick’s Mix

How to unpack a file using Process Explorer and WinDbg

One of the big issues when analyzing malicious files is that DLL’s and EXE’s are often packed using executable ‘packing’ software. Sometimes this software is well known, other times it is could be a custom compression software which makes it even more difficult to unpack.

While it can be very tedious and difficult to statically analyze a binary that has been packed, by its very nature, when executed the file must decrypt itself in order to execute on the system.

Using the latest version of Process Explorer (v12.04) and WinDbg, I have figured out at least 1 way to dump a DLL or EXE from the system’s loaded memory to a file. This version of the DLL or EXE written back to disk is not the same as the packed original, but is in fact the unpacked version that has been loaded into the system’s memory.

This technique is useful because it allows an analyst to review an unpacked version of the malicious file. Enough background, let’s begin.

In this example, we will be attempting to unpack a potentially malicious DLL. Virus Total currently shows that 6/41 AV Vendors detect this as a Trojan known as Win32.Hiloti.

I copied the file, “ezoyenaxixib.dll” to my c:\temp folder on my sandboxed system. The first step is to launch Process Explorer.

The next step is to actually load this DLL on my sandbox system. Because I was able to capture the registry entry for this file, I know the command it intended to use in order to have the system launch it at logon:

You may receive an error message that rundll32 could not find the entry point named “startup”. This is alright, but do NOT click OK. Doing so will cause rundll32.exe to close and to unload our malicious DLL. If you do mistakenly click OK, then just re-run the previous command.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Notice in the screenshot above that Process Explorer shows “rundll32.exe” as a child of cmd.exe, which we would expect since we launched it from a cmd prompt. Also notice that the command line shows rundll32.exe and our DLL.

Right-click on “rundll32.exe” in Process Explorer and select the Create Dump menu and select Create Full Dump …

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

For this example, we will save this file to c:\temp\rundll32_hiloti.dmp

Next, click again on “rundll32.exe” in order to highlight it. Now click on the View menu at the top of the Process Explorer Window and select the Lower Pane View menu and select DLLs:

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

(You also need to ensure that Show Lower Pane is checked). Notice that we now see our malicious DLL in the lower pane view. Go to the lower pane and right click on the malicious DLL and select Properties.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Once the properties dialog opens up, take note of 2 important pieces of information, the Load Address and the Mapped Size. Write these 2 values down if you need to.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

NOTE that if you click on the Strings tab and select the Memory radio button, you will see the strings embedded in the unpacked version of this DLL that is loaded into memory. Sometimes this is all you may be looking for, and can quit here.

But, if you’d like to write this unpacked version of the DLL loaded in memory to a file on disk, continue on!

At this point, we can close Process Explorer and click OK on the Rundll32 error dialog box. Next you will need to launch WinDbg, which is part of the freely downloadable Windows Debugging Tools.

Once WinDbg is open, click the File menu and select Open Crash Dump. In this case, I am going to load the crash dump that I created with Process Explorer earlier, and saved to c:\temp\rundll32_hiloti.dmp.

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

Now, with our crash dump loaded by WinDbg, we can start entering commands (where the red arrow is pointing above). We are going to execute the .writemem command which allows us to write a section of memory to a file. Enter the following:

.writemem c:\temp\unpacked_hiloti.dll 0x10000000 L47000

So what does this all mean?

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

How to unpack exe. Смотреть фото How to unpack exe. Смотреть картинку How to unpack exe. Картинка про How to unpack exe. Фото How to unpack exe

That’s it! At this point, you can now load the unpacked DLL into your favorite disassembler for further analysis.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *