|
|
Глава 32. Сокрытие PHP
В общем случае внесение неясности ненамного улучшает защищенность системы.
Но бывают случаи, когда следует использовать малейшую возможность.
Несколько несложных методик могут помочь вам скрыть PHP, что усложняет
работу потенциального взломщика, который пытается найти брешь в вашей
системе. Установив опцию expose_php = off в конфигурационном файле php.ini,
вы уменьшите количество доступной хакеру информации.
Еще одна методика заключается в настройке веб-сервера таким образом,
чтобы он обрабатывал файлы с различными расширениями как PHP-скрипты.
Это можно указать как в .htaccess файлах, так и конфигурационном файле Apache.
В таком случае вы сможете использовать при написании кода нестандартные расширения:
Пример 32-1. Маскировка PHP под другие языки программирования # Теперь PHP-скрипты могут иметь те же расширения, что и другие языки программирования
AddType application/x-httpd-php .asp .py .pl |
|
Или скрыть его совсем:
Пример 32-2. Использование неизвестных расширений для PHP-скриптов # Теперь PHP-скрипты могут иметь неизвестные типы файлов
AddType application/x-httpd-php .bop .foo .133t |
|
Также можно спрятать его под видом HTML-кода, что приведет к потере производительности,
так как все HTML файлы будут обрабатываться как PHP-код:
Пример 32-3. Маскировка PHP-кода под html-файлы # Теперь PHP-скртпы могут выглядеть как обыкновенный HTML
AddType application/x-httpd-php .htm .html |
|
Чтобы достичь желаемого эффекта, вы должны переименовать все ваши скрипты
в соответствии с выбранным вами расширением. Описанное в этом разделе документации
повышение безопасности через сокрытие PHP имеет мало недостатков при
небольших затратах.
Raz
24-Sep-2007 03:07
May some servers not allow you to put this line (i.e this not work)
AddType application/x-httpd-php .asp .py .pl
or
DefaultType application/x-httpd-php
so, the alternative method that really a good one is:
1- In your .htaccess file write:
RewriteEngine on
RewriteBase /dire/ or just /
RewriteRule securename yourfile\.php [T=application/x-httpd-php]
example: all url like
www.example.com/securename parsed as
www.example.com/yourfile.php
2- but here the $_GET not work, but $_POST work, so for dynamic pages like
www.example.com/yourfile.php?page=1 you use
www.example.com/securename?page=1
now: instead of using $_GET use
<?php
$uri = $_SERVER['REQUEST_URI'];
$page = strstr($uri, '=');
$page = substr($page, 1);
$valid_pages = array('1', '2','...');
$page = in_array($page, $valid_pages) ? $page : '1';
?>
and for bad URL you can add this code to .htaccess file
of coarse below the first code in .htaccess
#--
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ http://www.example.com/securename [L]
prrogers at gmail dot com
13-Sep-2007 08:50
The default session identifier-name PHPSESSID is publicly visible in an HTTP cookie and or URL if sessions are used. It can be changed in the php.ini to something more generic to further obscure PHP.
raven-3 [at] o2 [dot] pl
07-Mar-2007 11:23
I've found that your script ahmad does not work to me. So I've modified it, maybe someone will find it useful:
//default page
$config['main']="main";
//checking query
$QS=explode("&",$_SERVER['QUERY_STRING']);
$QS=explode('/',$QS[0]);
//we have to find out if main page is in Query string
//if not, then use default
if (!$QS[0]) $MODULE=$config['main'];
else $MODULE=strtolower($QS[0]);
//here everything take place
//below query is converted into table.
//use it like following: $_QUERY['theme']
for ($i=1;$i<count($QS);$i+=2) $_QUERY[$QS[$i]]=$QS[$i+1];
so eg link:
http://xyz.com/?projects/topic/20/theme/purple
means:
$module="projects";
$_QUERY['topic']=20;
$_QUERY['theme']="gray";
PS. I'm using PHP 4.4.2
rustamabd at google mail
26-Jan-2007 12:05
So far I haven't seen a working rewriter of /foo/bar into /foo/bar.php, so I created my own. It does work in top-level directory AND subdirectories and it doesn't need hardcoding the RewriteBase.
.htaccess:
RewriteEngine on
# Rewrite /foo/bar to /foo/bar.php
RewriteRule ^([^.?]+)$ %{REQUEST_URI}.php [L]
# Return 404 if original request is /foo/bar.php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule .* - [L,R=404]
# NOTE! FOR APACHE ON WINDOWS: Add [NC] to RewriteCond like this:
# RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$" [NC]
simon at carbontwelevedesign dot co dot uk
10-Aug-2006 05:31
I use the following in the .htaccess document
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
then the following simple code
<?php
$permalinks = explode("/",$_SERVER['REQUEST_URI']);
$varone = $permalinks[1];
$vartwo = $permalinks[2];
...
?>
marpetr at NOSPAM dot gmail dot com
11-Apr-2006 05:18
I think the best way to hide PHP on Apache and Apache itself is this:
httpd.conf
-------------
# ...
# Minimize 'Server' header information
ServerTokens Prod
# Disable server signature on server generated pages
ServerSignature Off
# ...
# Set default file type to PHP
DefaultType application/x-httpd-php
# ...
php.ini
------------
; ...
expose_php = Off
; ...
Now the URLs will look like this:
http://my.server.com/forums/post?forumid=15
Now hacker knows only that you are using Apache.
ahmad at unikomcenter dot com
05-Mar-2006 10:05
I am use this script to hidding PHP:
index.php
--------------
<?php
$QS=explode("&",$_SERVER['QUERY_STRING']);
$QS=explode('/',$QS[0]);
if (!$QS[0]) $MODUL='index';
else $MODUL=strtolower($QS[0]);
for ($i=1;$i<count($QS);$i+=2)
{
$_QUERY[$NVAR]=$NVAR=$QS[$i];
$$NVAR=$QS[$i+1];
}
if (!file_exists("modul_directory/{$MODUL}.php"))
$MODUL="index";
include("template.php");
include("modul_directory/{$MODUL}.php");
include("footer.php");
?>
we can access the modul in URL like this:
=================================
www.example.com/?forum/topic/20
- it mean load the modul forum.php, and set the _QUERY['topic']=20
www.foo.com/?voting/id/54/type/piechart&choice=2
- it mean load the modul voting.php, and set the _QUERY['id']=54 and _QUERY['type']='piechart' and set _GET['choice']=2
eric at ericwing dot net
20-Jan-2006 09:20
Something that has not been mentioned here is also the PHPSESSION id that will be displayed in the URL when passing it from page to page using GET. If users have cookies set to off, this will be visible. This can be reset before any session_start() call with ini_set(). Be aware however that this can't be changed in this way if you use autho session start.
dyer85 at gmail dot com
31-Dec-2005 12:55
Although it's probably obvious to most people, Yavuz Darendelioglu's post below utilizes a method that will only work on a *nix OS, not Windows, and probably not Mac.
Also, his regex uses some superfluous matching, instead, write the redirect like so: (you don't really need to use absolute path when redirecting to a resource on the same server, either):
RedirectMatch (?:awstats|xmlrpc) /deny.php
28-Dec-2005 07:29
Even you hide your PHP, requests for bugy scripts still come.
No matter whether you have the script on your server or not.
You can make an additional step for those requests. Since the host now trying that buggy script then, in the future when a new bug arises it will be tried by that host again with a high possibility. So banning that host completey at its first attempt may be a good idea. For this,
1- Add Permanent links for those requests in your httpd.conf:
RedirectMatch permanent (.*)awstats(.*)$ http://your_server/your_script.html
RedirectMatch permanent (.*)xmlrpc(.*)$ http://your_server/your_script.html
and add whatever you want to ban.
2- Write following code in your_script.html
<?
$host= $_SERVER['REMOTE_ADDR'];
$dropit = "iptables -A INPUT -i eth0 -p tcp -s $host -m multiport --destination-ports 80,25,22 -j DROP";
shell_exec($dropit);
exit
?>
Yavuz Darendelioglu
user at pampelhuber dot invalid
18-Dec-2005 04:32
It is unnecessary, to let every Pampelhuber inspect your 'php.ini' files.
Put the following into the .htaccess of your htdocuments' root:
#Obscure 'php.ini' files (where they exist)
RedirectMatch 404 .*php\.ini$
jtw90210
30-Jun-2005 01:19
In order to get the PATH_INFO to work in order to pass parameters using a hidden program/trailing slash/"pretty url" in more recent versions of PHP you MUST add "AcceptPathInfo On" to your httpd.conf.
AddType application/x-httpd-php .php .html
AcceptPathInfo On
Try it out with your phpinfo page and you'll be able to search for PATH_INFO.
http://yourserver.com/myphpinfo.php/showmetheway
If you want to drop the .php use one or both of these:
DefaultType application/x-httpd-php
ForceType application/x-httpd-php
25-May-2005 01:06
You could also do this in .htaccess when you use Apache and your configuration allows you to override :
<Files test>
ForceType application/x-httpd-php
</Files>
That way, you can use the URL test?pop=true without having to fake it by using test/index.php.
See the Apache manual for more info: http://httpd.apache.org/docs/mod/mod_mime#forcetype
benjamin at sonntag dot fr
24-May-2005 09:14
In response to the previous messages, for apache, there is a easier way to set files without "." to be executed by PHP, just put this in a ".htaccess" file :
DefaultType application/x-httpd-php
dimitar at bastun dot net
17-Jan-2005 09:13
In case there are an Internal Server error(error 500) using the old code below in an .htaccess file, you can replace it with the code modification that must solve the problem.
Old code
-----------
<Files ~ "^[^\.]+$">
ForceType application/x-httpd-php
</Files>
Replacement of the code above(code modification)
------------------------------------------------------------
AddHandler server-parsed .php
<Files ~ "^[^\.]+$">
SetHandler application/x-httpd-php
</Files>
Regards,
Dimitar Tanev
Nikolai-Zujev-(at)-Gmail-dot-Com
22-Sep-2004 12:22
Assign files w/o extension to php interpreter
without using ReWrite module
[clip httpd.conf]
<Files ~ "^[^\.]+$">
ForceType application/x-httpd-php
</Files>
[/clip]
|