downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Segurança do Sistema de Arquivos> <Caso 4: Interpretador do PHP fora da árvore de diretórios do servidor web
Last updated: Fri, 13 Nov 2009

view this page in

Instalado como módulo do Apache

Quando o PHP é usado como módulo do Apache, ele herda as permissões do usuário do Apache (normalmente as do usuário "nobody"). Isso tem vários impactos de segurança e autorização. Por exemplo, se você estiver usando o PHP para acessar um banco de dados, a menos que o banco de dados tenha um controle de acesso interno, você terá que faz o banco de dados acessível ao usuário "nobody". Isso significa que um script malicioso pode acessar e modificar o banco de dados, mesmo sem um usuário e senha. É possível que um web spider pode passar em uma página web de administração do banco de dados e remover todos os bancos de dados. Você pode se proteger contra isso usando autorização do Apache, ou você pode desenvolver seu modelo de acesso prório usando LDAP, arquivos .htaccess, etc. e incluir esse código como parte dos seus scripts PHP.

Normalmente, uma vez que a segurança está estabelecida até esse ponto onde o usuário do PHP (no caso, o usuário apache) tem pouco risco atribuído a ele, você descobre que o PHP não tem permissão de escrita nos diretórios dos usuários. Ou talvez tenha sido proibido de acessar ou alterar bancos de dados. Também foi proibido de escrever arquivos, bons ou ruins, ou fazer transações de bancos de dados, boas ou ruins.

Um erro freqüente de segurança feito até esse ponto é permiter ao apache permissões de administrador (root), ou aumentar as habilidades do apahce de qualquer outra forma.

Aumentar as permissões do usuário do Apache para a de administrador é extremamente perigoso e pode comprometer o sistema inteiro, então sudo'ing, chroot'ing, ou então executar como root não deve ser considerados por aqueles que não são profissionais em segurança.

Existem algumas soluções mais simples. Usando a diretiva open_basedir você pode controlar e restringir quais diretórios o PHP tem permissão de usar. Você também pode configurar area exclusivas para o Apache, restringir todas as atividades web para arquivo que não sejam de algum usuário ou do sistema.



add a note add a note User Contributed Notes
Instalado como módulo do Apache
Vikanich
14-Aug-2008 09:41
Big thanks to "daniel dot eckl at gmx dot de" but i have to change his config, because it doesn't work (may be wrong syntax).
I have add only this string to VirtualHost config and it works.
php_admin_value open_basedir  /www/site1/
Now all php scripts are locked in the directory.
Kibab
30-Sep-2005 11:56
I'm running Windows version of Apache with php as module. System is Windows XP Service Pack 2 on NTFS filesystem. To avoid potential security problems, I've set Apache to run under NT AUTHORITY\Network Service account, and there is only one directory, named Content, with Full Access for this account. Other directories are either not accessible at all or with readonly permissions (like %systemroot%)... So, even if Apache will be broken, nothing would happen to entire system, because that account doesn't have admin privilegies :)
tifkap
01-Mar-2004 09:21
There is a safe way to support a lot of users in a secure way, without having to use CGI, in a way which is probebly faster
than mod_php.

Use FastCGI, with the SuExecWrapper set to your suid wrapper. It means every user wil get his own program-group, with processes
which are being reused. If the numer of processes that is being
started on startup is 0, then the processgroup for a user will be generated when needed.

This means: The first page is slow, after that the Zend Engine  caching kicks in. When the load on the virtualhost reduces, the
processes wil die off, and extra processes for a user-process-group
will only be started when (again) needed.

Your apache will be a LOT! lichter, because it won't have to drag all
the php-memory overhead with it. This means static content is
faster, and the whole system uses less memory.
The PHP itself also won't need to drag along the apache overhead.

If for one reason or the other php craches, your apache will simple
start some new php-processes. If you want to upgrade/patch php,
you can simple create the new fastcgi binary, and after testing, you can simple update the system by copying it, and maybe doing a
'apachectl gracefull'

In short :  Sepparating distinct functions in different processes
                communicating useing IPC methodes can be very good
                for performance and security. The best example of this
                principle at work is Postfix, where every process runs
                chroot() under its own uid.

http://wiki.openisis.org/i/view/Php/HowtoFastCgi
Georgee at CWC
30-Apr-2003 11:16
Additional CAUTION to anyone trying Pollux's solution:
It's kind a good. Probably works right. I think I'll give it a try myself. BUT...
its safe ONLY on the assumption that apache is 100% CLEAN. (codes and confs.) Any flaws on apache, almost ANYTHING could happen to ALL users -precisely, web users. (Because apache is a member of ALL -again, web user's- GID.) So, leeps's hint should be one of the important things.

There is nothing close to perfect. What I wrote is just one thing you'll have to keep in mind. So, consider carefully BEFORE you try this solution. (Well, this applies to any other solutions though...)
leeps
10-Mar-2003 11:59
@pollux: additionally, tell your users to set their file-permissions to
- r-- (group) for files
- --x (group) for directories.

this disables the webserver to browse user's directory. if you don't know the filename, you cannot open it, e.g. by running malicious php-code through one of the users scripts.
daniel dot eckl at gmx dot de
08-Aug-2002 09:16
There is a better solution than starting every virtual host in a seperate instance, which is wasting ressources.

You can set open_basedir dynamically for every virtual host you have, so every PHP script on a virtual host is jailed to its document root.

Example:
<VirtualHost www.example.com>
  ServerName www.example.com
  DocumentRoot /www-home/example.com
[...]
  <Location />
    php_admin_value open_basedir     \ "/www-home/example.com/:/usr/lib/php/"
  </Location>
</VirtualHost>

If you set safe_mode on, then the script can only use binaries in given directories (make a special dir only with the binaries your customers may use).

Now no user of a virtual host can read/write/modify the data of another user on your machine.

Windseeker

 
show source | credits | sitemap | contact | advertising | mirror sites