Php safe mode linux

Безопасный режим

Безопасный режим в PHP — это попытка решить проблему безопасности на совместно используемых серверах. Несмотря на то, что концептуально неверно решать эту проблему на уровне PHP, но поскольку альтернативы уровня веб-сервера или операционной системы на сегодняшний день отсутствуют, многие пользователи, особенно провайдеры, используют именно защищенный режим.

Данная возможность была объявлена УСТАРЕВШЕЙ, начиная с PHP 5.3.0 и была УДАЛЕНА в PHP 5.4.0.

История изменений режима safe mode

Версия Описание
5.4.0 Удален из PHP, генерирует фатальную ошибку E_CORE_ERROR при попытке включения.
5.3.0 Помечен устаревшим, при включении генерируется ошибка уровня E_DEPRECATED .

User Contributed Notes 14 notes

Note that safe mode is largely useless. Most ISPs that offer Perl also offer other scripting languages (mostly Perl), and these other languages don’t have the equivalent of PHP.
In other words, if PHP’s safe mode won’t allow vandals into your web presence, they will simply use Perl.
Also, safe mode prevents scripts from creating and using directories (because they will be owned by the WWW server, not by the user who uploaded the PHP script). So it’s not only useless, it’s also a hindrance.
The only realistic option is to bugger the Apache folks until they run all scripts as the user who’s responsible for a given virtualhost or directory.

Читайте также:  Python выполнить http запрос

zebz: The user would not be able to create a directory outside the namespace where he/she would be able to modify its contents. One can’t create a directory that becomes apache-owned unless one owns the parent directory.

Another security risk: since files created by apache are owned by apache, a user could call the fputs function and output PHP code to a newly-created file with a .php extension, thus creating an apache-owned PHP script on the server. Executing that apache-owned script would allow the script to work with files in the apache user’s namespace, such as logs. A solution would be to force PHP-created files to be owned by the same owner/group as the script that created them. Using open_basedir would be a likely workaround to prevent ascension into uncontrolled areas.

readfile() seems not always to take care of the safe_mode setting.
When the file you want to read with readfile() resides in the same directory as the script itself, it doesn`t matter who the owner of the file is, readfile() will work.

Many filesystem-related functions are not appropriately restricted when Safe Mode is activated on an NT server it seems. I would assume that this is due to the filesystem not making use of UID.

In all of my scripts, no matter WHO owns the script (file Ownership-wise) or WHO owns the directory/file in question; both UIDs display

(getmyuid() and fileowner()) as UID = 0

This has the rather nasty side effect of Safe Mode allowing multiple filesystem operations because it believes the script owner and file/dir owner are one and the same.

While this can be worked around by the judicious application of proper filesystem privileges, it’s still a «dud» that many of Safe Mode’s securities are simply not there with an NT implementation.

Each IIS server in Windows runs as a User so it does have a UID file ACLs can be applied via a Group (GID) or User. The trick is to configure each website to run as a distinct user instead of the default of System.

All the filesystem-related functions (unlink, fopen, unlink, etc) seems to be restricted the same way in safe mode, at least on PHP 4.2. If the file UID is different *but* the directory (where the file is located) UID is the same, it will work.

So creating a directory in safe mode is usually a bad idea since the UID will be different from the script (it will be the apache UID) so it won’t be possible to do anything with the files created on this directory.

On the note of php security

suPHP is a tool for executing PHP scripts with the permissions of their owners. It consists of an Apache module (mod_suphp) and a setuid root binary (suphp) that is called by the Apache module to change the uid of the process executing the PHP interpreter.

Sometimes you’re stuck on a system you don’t run and you can’t control the setting of safe mode. If your script needs to run on different hosts (some with safe mode, some without it), you can code around it with something like:

// Check for safe mode
if( ini_get ( ‘safe_mode’ ) ) // Do it the safe mode way
>else // Do it the regular way
>

Beware that when in safe mode, mkdir creates folders with apache’s UID, though the files you create in them are of your script’s UID (usually the same as your FTP uid).

What this means is that if you create a folder, you won’t be able to remove it, nor to remove any of the files you’ve created in it (because those operations require the UID to be the same).

Ideally mkdir should create the folder with the script’s UID, but this has already been discussed and will not be fixed in the near future.

In the meantime, I would advice NOT to user mkdir in safe mode, as you may end up with folders you can’t remove/use.

Just to note, I created patch which allows VirtualHost to set User under which all (PHP too) runs. It is more secure than safe_mode. See luxik.cdi.cz/~devik/apache/ if you are interested

Источник

Безопасность и безопасный режим

Включает/отключает безопасный режим в PHP. Если PHP скомпилирован с опцией —enable-safe-mode, то по умолчанию принимает значение On (включено), иначе — Off (выключено).

Данная возможность была помечена УСТАРЕВШЕЙ начиная с версии PHP 5.3.0 и была УДАЛЕНА в версии PHP 5.4.0.

По умолчанию в безопасном режиме при открытии файла выполняется проверка значения UID. Для того, чтобы немного смягчить это условие и выполнять проверку GID, необходимо установить значение on для флага safe_mode_gid. Определяет, использовать ли проверку UID ( FALSE ) или GID ( TRUE ) проверку при обращении к файлу.

При подключении файлов, расположенных в указанной директории и всех ее подкаталогах, проверка на соответствие значений UID/GID не выполняется (в случае, если установленная директория не указана в include_path, необходимо указывать полный путь при включении).

Значением этой директивы может быть список каталогов, разделенных двоеточием (точкой с запятой на Windows-системах), что аналогично синтаксису include_path. Указанное значение в действительности является префиксом, а не названием директории. Это означает, что запись «safe_mode_include_dir = /dir/incl» позволяет подключать файлы, находящиеся в директориях «/dir/include» и «/dir/incls«, в случае, если они существуют. Если вы хотите указать доступ к конкретной директории, используйте завершающий слеш, например: «safe_mode_include_dir = /dir/incl/» Если значение этой директивы пусто, то никакие файлы с отличающимися UID/GID не могут быть подключены. safe_mode_exec_dir string

В случае, когда PHP работает в безопасном режиме, system() и другие функции запуска программ отклоняют выполнение программ, находящихся вне данной директории. Вам также придется использовать / в качестве разделителя пути на всех окружениях, включая Windows.

Возможность устанавливать переменные окружения — потенциальная брешь в безопасности. Значением этой директивы является список префиксов, разделенных двоеточиями. В безопасном режиме пользователь может модифицировать только те переменные окружения, имена которых начинаются с одного из указанных префиксов. По умолчанию, пользователю доступны переменные, которые начинаются с префикса PHP_ (например, PHP_FOO=BAR).

Замечание:

В случае, если этой директиве указать пустое значение, пользователь получит возможность модифицировать ЛЮБУЮ переменную окружения!

Эта директива содержит список переменных окружения, разделенных двоеточием, значение которых пользователь не сможет изменить, используя функцию putenv() . Значения этих переменных остаются защищенными, даже если их модификация разрешена директивой safe_mode_allowed_env_vars.

В случае, если включена директива safe_mode, PHP проверит, совпадает ли владелец скрипта и владелец файла или директории, которыми оперирует скрипт. Например:

-rw-rw-r-- 1 rasmus rasmus 33 Jul 1 19:20 script.php -rw-r--r-- 1 root root 1116 May 26 18:01 /etc/passwd
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

Тем не менее, предусмотрена возможность вместо проверки на соответствие UID использовать более мягкую проверку на соответствие GID. Для этого необходимо использовать директиву safe_mode_gid. В случае, если она установлена значением On, используется более мягкая проверка GID. В противном случае, если установлено значение Off (значение по умолчанию), выполняется более строгая проверка на соответствие UID.

В качестве альтернативы директиве safe_mode вы можете ограничить все выполняемые скрипты жестко заданным деревом директорий при помощи опции open_basedir. Например (фрагмент конфигурационного файла httpd.conf ):

 php_admin_value open_basedir /docroot 

При попытке выполнить тот же самый скрипт script.php с указанной опцией open_basedir вы получите следующий результат:

Warning: open_basedir restriction in effect. File is in wrong directory in /docroot/script.php on line 2

Вы также можете запретить отдельные функции. Следует заметить, что директива disable_functions может быть указана исключительно в конфигурационном файле php.ini , это означает, что вы не можете, отредактировав httpd.conf , установить индивидуальные значения для конкретного виртуального хоста или каталога. Если добавить в php.ini следующую строку:

disable_functions = readfile,system
Warning: readfile() has been disabled for security reasons in /docroot/script.php on line 2

Разумеется, эти ограничения PHP не работают в запускаемых программах.

Источник

How to Enable and Disable PHP Safe Mode in Linux

The PHP safe mode is an attempt to solve the shared-server security problem. When safe mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function or its directory. For example:

-rw-rw-r— 1 sam sam 33 Jul 1 19:20 test.php
-rw-r—r— 1 root root 1116 May 26 18:01 /etc/passwd

results in this error when safe mode is enabled:

Warning: SAFE MODE Restriction in effect. The script whose uid is 600 is not
allowed to access /etc/passwd owned by uid 0 in /home/www/script.php on line 2.

But, safe mode restrictions often results in many problems and reduced performance. The Content Management Systems like “Joomla installation” will not work when safe mode is enabled. The core problem with safe mode is its inconsistency; some basic functions required by web scripts would simply not work with PHP safe mode enabled. Because of the limitations, this feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

In order to enable or disable safe mode, you need to edit the PHP configuration file, php.ini.

1) Find the location of system php.ini file

Execute the following command to find the php.ini location:

2) Add the following line in php.ini

3) Test it with the help of phpinfo.php

Contents of phpinfo.php script:

The other security measures provided by PHP — open_basedir and disable_functions — can be used as an alternative to safe_mode.

Conclusion

In this tutorial we learned how to enable and disable php safe mode in linux. Hope you enjoyed reading this and please leave your suggestions in the below comment section.

linoxide

Источник

Оцените статью