Если PHP установлен как модуль Apache

Когда PHP используется как модуль Apache, он наследует права пользователя, с которыми был запущен веб-сервер (обычно это пользователь 'nobody'). Это влияет на обеспечение безопасности и реализацию авторизации. Например, если вы используете базу данных, которая не имеет встроенного механизма разграничения доступа, вам прийдется обеспечить доступ к БД для пользователя 'nobody'. В таком случае зловредный скрипт может получить доступ к базе данных и модифицировать ее, даже не зная логина и пароля. Вполне возможна ситуация, когда веб-паук неверными запросами страницы администратора базы данных уничтожит все данные или даже структуру БД. Вы можете избежать такой ситуации при помощи авторизации Apache или разработав собственную модель доступа, используя LDAP, файлы .htaccess или любые другие технологии, внедряя соответствующий код в ваши скрипты.

Достаточно часто используются такие настройки безопасности, при которых PHP (имеется ввиду пользователь, с правами которого выполняется Apache) имеет минимальные привелегии, например отсутствует возможность записи в пользовательские директории. Или, например, отсутствует возможность работать с базой данных. При этом система безопасности не позволяет записывать как "хорошие", так и "плохие" файлы, аналогично позволяет производить как "хорошие", так и "плохие" транзакции.

Распространенной ошибкой является запуск Apache с правами суперпользователя или любое другое расширение полномочий веб-сервера.

Расширение привилегий веб-сервера до полномочий угрожает работоспособности всей системы, такие команды, как sudo, chroot должны выполняться исключительно теми, кто считает себя профессионалами в вопросах безопасности.

Существует несколько простых решений. Используя open_basedir, вы можете ограничить дерево доступных директорий для PHP. Вы так же можете определить область доступа Apache, ограничив все веб-сервисы не-пользовательскими или не-системными файлами.

Коментарии

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
2002-08-08 07:16:41
http://php5.kiev.ua/manual/ru/security.apache.html
Автор:
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 :)
2005-09-30 09:56:01
http://php5.kiev.ua/manual/ru/security.apache.html
Автор:
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.
2008-08-14 07:41:53
http://php5.kiev.ua/manual/ru/security.apache.html
Автор:
doc_root already limits apache/php script folder locations.

open_basedir is better used to restrict script access to folders
which do NOT contain scripts. Can be a sub-folder of doc_root as in php doc example doc_root/tmp, but better yet in a separate folder tree, like ~user/open_basedir_root/. Harmful scripts could modify other scripts if doc_root (or include_path) and open_basedir overlap.
If apache/php can't browse scripts in open_basedir, even if malicious scripts uploaded more bad scripts there, they won't be browse-able (executable). 

One should also note that the many shell execute functions are effectively a way to bypass open_basedir limits, and such functions should be disabled if security demands strict folder access control. Harmful scripts can do the unix/windows version of "delete */*/*/*" if allowed to execute native os shell commands via those functions. OS Shell commands could similarly bypass redirect restrictions and upload file restrictions by just brute force copying files into the doc_root tree. It would be nice if they could be disabled as a group or class of functions, but it is still possible to disable them one by one if needed for security.

PS. currently there is a bug whereby the documented setting of open_basedir to docroot/tmp will not work if any include or require statements are done. Right now include will fail if the included php file is not in BOTH the open_basedir tree and the doc_root+include_path trees. Which is the opposite of safe.
This means by any included php file must be in open_basedir, so is vulnerable to harmful scripts and php viruses like Injektor.
2012-02-24 07:17:38
http://php5.kiev.ua/manual/ru/security.apache.html
Автор:
It is not useful for ordinary users to have a debate about the lack of security in using PHP without clearly listing step by step methods of resolving the issue. Such methods should be authoritatively provided by PHP and not as a user's opinion, later debated by another user.

It is not that I am opposed to debate. This is how we learn as an open-source community.  However, us mere mortals need the gods of PHP to come to conclusions and give us best practices.
2022-03-12 17:59:03
http://php5.kiev.ua/manual/ru/security.apache.html

    Поддержать сайт на родительском проекте КГБ