Copy Link
Add to Bookmark
Report

451: Inspector v 1.666

eZine's profile picture
Published in 
451
 · 21 May 2022

Inspector v 1.666

"... A long pause - and the surviving two
phone. A relay has closed somewhere. Two telephone
the voices connected directly to each other.
Hello, Barton?
Yes, Barton?
- I'm twenty-four.
- I'm twenty-six. We are both young. What's wrong?
- I do not know. Listen..."

(c) Bradbury R. "Night Call"


That's all over. It turned out something that combines permutation and encryption, and, well, a utility for encrypting PE files. But is it over? And will it ever end? Probably not, and it pleases ...


Inspector

As already mentioned, inpector is a utility for encrypting PE files, as a key for encryption / decryption, a phrase entered from the console is used, of which only the first 16 characters are taken into account. What is actually used is a 64-bit key, which is the result of an XOR of both 8-byte parts of the key. InPEctor ? this is not a packer/cryptor, which only prevents you from getting into the program code, but allows everyone to run the program. Unlike cryptors, the utility is intended for the one who uses the program. The encrypted program can only be used by those who know the password.

For cryptography, Blowfish was chosen for its speed, transparent implementation and lack of data necessary for its operation. Encryption takes place in CBC mode i.e. when the current data block is XORed with the previous one and encrypted, and so on until the end of the data.

The code section, data and imports are subject to encryption. After that, a new section is added to the file, containing a decryptor/loader, to which the RVA of the PE will be adjusted.

As a result of these operations:

  • The file cannot be launched without knowing the key.
  • Unable to determine what the program is - code, data and imports are unknown, i.e. all items that indicate in some way the actions of the program.
  • The disk contains only an encrypted file, decryption takes place directly in memory. But this circumstance does not allow installers/encryptors to encrypt.

Loader/decryptor actions

  • 0. Get the key.
  • 1. Try to decrypt some sections.
  • 2. Download all used libraries and set up import.
  • 4. If required, use fixups and set up addresses.
  • 5. If there is a Tls callback, then go through the list of functions.
  • 6. Transfer control to the program.

Of course, you can trace the decryptor, but the key is naturally not stored in it, but only crc32 is stored for each section. Those. after entering the passkey, the entire section is decrypted, then the crc of the decrypted section and the original one is compared, and if something is wrong, then everyone rests. Why not crc key? And in order to make it impossible to just pick up a key that satisfies this crc. crc can be calculated much faster than decrypting an entire section.

So that there is no desire to analyze the decryptor, it is simply permuted using LTME .


About limitations and problems

First of all, it must be said that neither resources nor exports are encrypted, and they are rarely used in programs that are usually encrypted ;). In general, all sections are not encrypted, except for those indicated by pointers in the file header, called Base of Code, Base of Data, Import Table RVA.

If there is TLS, then the address of the TLS index changes, then the callback in the header is filled with zero, and the callback procedures are loaded by the decryptor "manually".

If the program has sections with a non-aligned physical size, then it is not subject to encryption - the sections are somehow not loaded by windows as it is written in the title, and therefore it is better not to risk it.

Sections are assumed to follow in memory and in the file as specified in the section table. And there should be enough space between the header and the first section to add a decryptor section descriptor.

Because changes RVA, then it must not be 0, otherwise such a file is not considered as a candidate for encrypted.

Apparently, win2k does not load programs without imports, and because. imports are configured with a decryptor, and the header is set to 0 , so encrypted files will not run on win2k.


original russian version


Inpector v 1.666

"... Долгая пауза - и зазвонили уцелевшие два
телефона.Где-то замкнулось реле. Два телефонных
голоса соединились напрямую друг с другом.
- Алло, Бартон?
- Да, Бартон?
- Мне двадцать четыре.
- А мне двадцать шесть. Мы оба молоды. Что стряслось?
- Не знаю. Слушай..."

(c) Bradbury R. "Night Call"

Вот все и закончилось. Получилось что-то сочетающее в себе пермутацию и шифрование, ну и утилита для шифрования PE-файлов. Но закончилось ли? И вообще что-нибудь закончится? Наверное нет, и это радует...


Inpector

Как уже было сказано, inpector это утилита для криптовки PE-файлов, в качестве ключа, для шифрования/дешифрования, используется фраза, введенная с консоли,из которой учитываются только первые 16 символов. Реально же используется 64-битный ключ, являющийся результатом XOR'а обеих 8-байтных частей ключа.InPEctor ? это не упаковщик/криптор, который лишь не дает залезть в код программы, но позволяет запустить программу всем .В отличие от крипторов утилита предназначена для того, кто использует программу. Закриптованую программу могут использовать лишь те, кто знает пароль.

Для криптовки был выбран Blowfish за его скорость, прозрачную реализацию и отсутствие необходимых для его работы данных. Шифрование происходит в режиме CBC т.е. когда текущий блок данных XOR'ится с предыдущим и шифруется, и так до конца данных.

Шифрованию подлежат кодовая секция, данные и импорты. После этого в файл дописывается новая секция, содержащая декриптор/загрузчик, на который и будет скорректирован RVA PE-шника.

В результате этих операций:

  • Файл невозможно запустить без знания ключа.
  • Невозможно определить, что представляет собой программа - код, данные и импорты неизвестны, т.е. все пункты, указывающие неким образом на действия программы.
  • На диске содержится лишь криптованый файл, расшифровка происходит непосредственно в памяти. Но это обстоятельство не дает шифровать инсталляторы/шифровщики.

Действия загрузчика/декриптора:

  • 0. Получить ключ.
  • 1. Попытаться декриптовать некоторые секции.
  • 2. Загрузить все используемые библиотеки и настроить импорт.
  • 4. Если требуется,то использовать фиксапы и настроить адреса.
  • 5. Если есть Tls callback ,то пройти по списку функций.
  • 6. Передать управление программе.

Конечно, можно потрассировать декриптор, но ключ естественно не хранится в нем,а хранится лишь crc32 на каждую секцию. Т.е. после ввода passkey'я происходит декриптовка всей секции, затем сравнивается crc декриптованой секции и оригинальной и если что-то не так, то все отдыхают. Почему не crc ключа? А для того, чтобы нельзя было просто подобрать ключ, удовлетворяющий этому crc т.к. crc можно подсчитать намного быстрее, чем декриптовать целую секцию.

Чтобы не было желания анализировать декриптор, он просто-напросто пермутируется с помощью LTME.


Об ограничениях и проблемах

Сперва надо сказать о том, что ни ресурсы, ни экспорт не криптуются, да и редко они используются в обычно подлежащих криптовке программах ;). Вообще не криптуются все секции, кроме тех, на которые указывают поинтеры в заголовке файла, именуемые Base of Code,Base of Data,Import Table RVA.

Если есть TLS ,то адрес индекса TLS меняется, далее callback в заголовке забивается нулем, а callback-процедуры грузятся декриптором "вручную".

Если программка имеет секции с невыровненым физическим размером, то она не подлежит криптовке - секции как-то не так грузятся windows ,как прописано в заголовке и поэтому лучше не рисковать.

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

Т.к. изменяется RVA ,то он должен быть не 0 ,иначе такой файл не рассматривается как кандидат в зашифрованные.

Судя по всему, win2k не грузит программы без импортов и т.к. импорты настраиваются декриптором, а в заголовке стоит 0 ,то таким образом зашифрованные файлы не будут запускаться на win2k.

← 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