PHP中的安全模式safe_mode

Safe Mode(安全模式)

打开Safe Mode的首页http://php.net/manual/en/features.safe-mode.php

我们发现醒目的警告:

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

这个特性在5.3后不推荐使用,在5.4中删除。原来safe mode已经是明日黄花了。

那么,safe mode是做什么用的呢?

PHP 的安全模式是为了试图解决共享服务器(shared-server)安全问题而设立的。在结构上,试图在 PHP 层上解决这个问题是不合理的,但修改 web 服务器层和操作系统层显得非常不现实。因此许多人,特别是 ISP,目前使用安全模式。

safe_mode是PHP_INI_SYSTEM属性,必须通过php.ini来设置。

要启用safe_mode,只需修改php.ini: safe_mode = On 重启后就生效了。

启动safe_mode,会对许多PHP函数进行限制,特别是和系统相关的文件打开、命令执行等函数,所有操作文件的函数将只能操作与脚本UID相同的文件。

safe mode相关参数如下:

Security and Safe Mode Configuration Directives
NameDefaultChangeableChangelog
safe_mode“0″PHP_INI_SYSTEMRemoved in PHP 5.4.0.
safe_mode_gid“0″PHP_INI_SYSTEMAvailable since PHP 4.1.0. Removed in PHP 5.4.0.
safe_mode_include_dirNULLPHP_INI_SYSTEMAvailable since PHP 4.1.0. Removed in PHP 5.4.0.
safe_mode_exec_dir“”PHP_INI_SYSTEMRemoved in PHP 5.4.0.
safe_mode_allowed_env_vars“PHP_”PHP_INI_SYSTEMRemoved in PHP 5.4.0.
safe_mode_protected_env_vars“LD_LIBRARY_PATH”PHP_INI_SYSTEMRemoved in PHP 5.4.0.

而下面这个链接则显示了被safe_mode组织或者禁用的函数。http://www.php.net/manual/en/features.safe-mode.functions.php

实例演示

当 safe_mode 设置为 on,PHP 将通过文件函数或其目录检查当前脚本的拥有者是否和将被操作的文件的拥有者相匹配。例如:

4 -rw-r–r– 1 httpd root    72 2012-04-16 00:51 test.php
4 -rw-r–r– 1 root root 1853 2012-03-28 16:20 /etc/passwd

运行 test.php

<?php
fopen(‘/etc/passwd’,’r’);
readfile(‘/etc/passwd’);
mkdir(‘test’);

如果安全模式被激活,则将会导致以下错误:

Warning: fopen() [function.fopen]: SAFE MODE Restriction in effect. The script whose uid is 1003 is not allowed to access /etc/passwd owned by uid 0 in /usr/local/httpd/htdocs/test.php on line 2

后记:有一点要提醒一下:很多人把open_basedir当成safe_mode的一个子功能,其实不然,PHP官网中明确表示:

Limit the files that can be opened by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.

将 PHP 所能打开的文件限制在指定的目录树,包括文件本身。本指令不受安全模式打开或者关闭的影响。

相关的文章:

暂无评论

写评论