Copy Link
Add to Bookmark
Report

451: Dirty Entrypoint Engine (DEE) v 1.32

eZine's profile picture
Published in 
451
 · 19 Apr 2022

The DEE engine is a variation on the UEP theme. This technology involves "cutting" some command into a random place in the program code, usually jumping to the body of the virus. This technique makes it possible to claim that the virus is incurable, but in reality it can only complicate its detection. Suppose that UEP implements the replacement of a command at a random address in the program with something else - replacing it with jmp / call in a virus), but it is necessary that the length of the "embedded" command be less than or equal to the original one, because otherwise, the “embedded” command can ruin the one that follows it.

Finding addresses for replacement can be implemented in various ways, but the main directions are relocations and partial reversing, the DEE engine implements the latter.

DEE does not replace anything - let others replace it, and its job is to find commands according to the required characteristics and return as a result the address in the source buffer, randomly selected from those found, of a command that satisfies the search.

Call Format

DWORD DEE( 
VOID* code_param, // code buffer
DVORD cnt, // number of views
// byte

VOID* *MALLOC ( // memory "allocator"
DWORD cnt // number of bytes
),

VOID* FREE ( // memory "releaser"
VOID buffer // pointer to buffer
),

DWORD* RND ( // RNG
DWORD* seed, // pointer to initializer
DWORD range // limit
),
DWORD* seed, // pointer to initializer
// RNG

DWORD* dasm ( // disassembler
VOID* ibuf, // input buffer
DWORD reserved, // not used
VOID* tables // table pointer
),

VOID* dasm_tables, // table pointer
// disassembler

DWORD flags // flags
);


C call is used for the call, i.e. parameters are passed in reverse order and the function does not clear the stack.

The result of execution - the address of the command in the buffer is returned in EAX , on error the return value is FFFFFFFFh.

Flags can be:

  • DEE_CMD5 00000001 search for all commands besides CALL, size >= 5 byte
  • DEE_LINKS 00000002 use JMP links.

Work algorithm

The engine's actions are to find CALLs, as an option (with setting the appropriate flags) - search for commands whose length is greater than or equal to 5 bytes.

This is done by sequentially disassembling the buffer using an external disassembler. Then the engine randomly takes any of the found addresses and returns this address as a function response. Because If a buffer address is passed to DEE, then the absolute address of the instruction in the buffer is given at the output, not its RVA relative to the buffer. It seems to be more versatile.

During operation, the engine uses memory, and the number of bytes required is cnt*4*2. For a sufficiently large program, this can be a lot and there is a possibility of a lack of memory, in which case DEE will return FFFFFFFF at the output, now it’s worth reducing сnt, thereby limiting the number of bytes viewed, and repeat everything again, and then, in case of an error, again and so until it sucks.

With the LINKS flag turned on, when a relative JMP is encountered, disassembly continues at the address it points to. In this case, you should load the entire code section into the buffer, or better, the entire image with imitation of loaded sections, because there may be files with code in the data, although this is unlikely.
Otherwise, there is a risk of going beyond the buffer.
In order to find commands that are most likely to be launched at the start of the program, when all sorts of RETs, absolute transitions, etc. are encountered, the search for commands stops and the command is selected from those found before. As practice has shown, this somewhat reduces the percentage of infection, with which the virus does not start.

That seems to be all.

Unseek & grow!

Dirty Entrypoint Engine (DEE) v 1.32

Движок DEE является вариацией на тему UEP. Данная технология подразумевает "врезание" в случайное место кода программы какой-то команды, обычно перехода на тело вируса.Такая техника позволяет претендовать на неизлечимость вируса, но реально может только усложнить его детектирование. Допустим, что UEP реализует замену команды по случайному адресу в программе на что-либо иное вариант - замена на jmp/call в вирус), но необходимо, чтобы длина "врезанной" команды была меньше, либо равной исходной т.к. в противном случае “врезанная” команда может испортить последующую за ней.

Нахождение адресов для замены может быть реализовано различными способами, но основные направления - релокейшены и частичный реверсинг, движок DEE реализует второе.

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


Формат вызова

DWORD DEE ( 
VOID* code_param, // буфер с кодом
DVORD cnt, // количество просматриваемых
// байт

VOID* *MALLOC ( // "аллокатор" памяти
DWORD cnt // количество байт
),

VOID* FREE ( // "релизер" памяти
VOID bufer // поинтер на буфер
),

DWORD* RND ( // ГСЧ
DWORD* seed, // поинтер на инициализатор
DWORD range // предел
),
DWORD* seed, // поинтер на инициализатор
// ГСЧ

DWORD* dasm ( // дизассемблер
VOID* ibuf, // входной буфер
DWORD reserved, // не используется
VOID* tables // поинтер на таблицы
),

VOID* dasm_tables, // поинтер на таблицы
// дизассемблера

DWORD flags // флаги
);


Для вызова используется C call, т.е. параметры передаются в обратном порядке и функция не очищает стек.

Результат выполнения - адрес команды в буфере возвращается в EAX ,при ошибке возвращаемое значение равно FFFFFFFFh.

Флаги могут быть следующими:

DEE_CMD5	00000001	искать помимо CALL все команды, размером >= 5 байт 
DEE_LINKS 00000002 использовать переходы по JMP'ам.


Алгоритм работы

Действия движка заключаются в нахождении CALL'ов, как вариант (с заданием соответствующих флагов) - поиск команд, длина которых больше либо равна 5 байтам.

Это осуществляется посредством последовательного дизасма буфера с помощью внешнего дизассемблера. Затем движок берет рандомом любой из найденных адресов и как ответ функции возвращает этот адрес. Т.к. в DEE передается адрес буфера, то на выходе отдается абсолютный адрес команды в буфере, а не ее RVA относительно буфера. Это кажется более универсальным.

В процессе работы движок использует память, и количество требуемых байт составляет cnt*4*2. Для достаточно большой программы это может быть много и есть вероятность нехватки памяти, в таком случае DEE вернет на выходе FFFFFFFF, теперь стоит уменьшить сnt ,тем самым ограничив количество просматриваемых байт, и повторить все снова, а потом, в случае ошибки, еще раз и так пока не заебет.

С включенным флагом LINKS при встрече относительного JMP'а,дизассемблирование продолжается по адресу, куда он указывает. В таком случае, следует грузить кодовую секцию в буфер полностью, а лучше весь имадж с имитацией загруженных секций, т.к. могут быть и файлы с кодом в данных, хотя это и маловероятно.
Иначе есть риск выйти за пределы буфера.
Для того ,чтобы совершить нахождние команды ,котороая вероятнее всего запустится при старте программы ,при встрече всяких там RET'ов ,абсолютных переходов и пр. поиск команд прекращается и команда выбирается из найденных до этого.Как показала практика это несколько понижает процент заражения,при котором вирус не запускается.


Вот вроде бы и все.

Unseek & grow!

← previous
next →
loading
sending ...
New to Neperos ? Sign Up for free
download Neperos App from Google Play
install Neperos as PWA

Let's discover also

Recent Articles

Recent Comments

Neperos cookies
This website uses cookies to store your preferences and improve the service. Cookies authorization will allow me and / or my partners to process personal data such as browsing behaviour.

By pressing OK you agree to the Terms of Service and acknowledge the Privacy Policy

By pressing REJECT you will be able to continue to use Neperos (like read articles or write comments) but some important cookies will not be set. This may affect certain features and functions of the platform.
OK
REJECT