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

search for in the

안전 모드에 의해 제한되는/비활성화되는 함수들> <영구적인 데이터베이스 접속
Last updated: Sun, 25 Nov 2007

view this page in

안전 모드

Table of Contents

PHP 안전 모드는 공유-서버 보안 문제를 풀려는 시도이다. 이 문제를 PHP 수준에서 풀려고 하는것은 구조적으로 올바르지 않다. 그러나 웹서버와 OS 수준에서의 차선책이 아주 현실적이지는 않기 때문에, 많은 사람, 특히 ISP, 들이 현재 안전 모드를 사용한다.

보안과 안전 모드

보안과 안전 모드 설정 지시어
지시어명 기본값 변경값
safe_mode "0" PHP_INI_SYSTEM
safe_mode_gid "0" PHP_INI_SYSTEM
safe_mode_include_dir NULL PHP_INI_SYSTEM
safe_mode_exec_dir "" PHP_INI_SYSTEM
safe_mode_allowed_env_vars PHP_ PHP_INI_SYSTEM
safe_mode_protected_env_vars LD_LIBRARY_PATH PHP_INI_SYSTEM
open_basedir NULL PHP_INI_SYSTEM
disable_functions "" PHP_INI_SYSTEM
disable_classes "" PHP_INI_SYSTEM
PHP_INI_* 상수에 대한 좀 더 자세한 설명과 정의를 보기 위해서는 ini_set() 참조.

위 설정 지시어에 대한 간단한 설명입니다.

safe_mode boolean

PHP의 안전 모드 활성화 여부. 더 자세한 정보는 보안 장을 참고.

safe_mode_gid boolean

기본값, 안전 모드는 파일이 열릴 때 UID 비교 검사를 수행한다. 이 설정을 GID 비교로 완화하려면, safe_mode_gid을 켜도록 한다. 파일 접근에 대해 UID (FALSE) 검사를 하는지, GID (TRUE) 검사를 하는지의 여부.

safe_mode_include_dir string

이 디렉토리와 하위디렉토리에서 파일을 include할 때에는 UID/GID 검사가 무시된다 (디렉토리는 include_path나 include되는 전체 경로가 되어야 한다).

PHP 4.2.0부터 이 지시어는 include_path 지시어와 같은 방식으로, 콜론(윈도우에서는 세미콜론)으로 구분하여 복수의 경로를 가질 수 있습니다. 설정 제한은 실질적으로 디렉토리명이 아닌 앞첨자(prefix)가 된다. 이말의 의미는 "safe_mode_include_dir = /dir/incl"는 "/dir/include"와 "/dir/incls"가 존재하기만 한다면 그 디렉토리도 접근이 허용된 다는 것이다. 특정 디렉토리만으로 접근을 제한하고자 하면, 슬래시로 끝내면 된다. For example: "safe_mode_include_dir = /dir/incl/"
safe_mode_exec_dir string

PHP가 안전 모드를 사용중이라면, system()과 그 외의 시스템 프로그램을 실행하는 함수는 이 디렉토리에 있지 않으면 프로그램 시작이 거부된다.

safe_mode_allowed_env_vars string

특정 환경 변수를 설정하는것은 잠재적인 보안 구멍이 될수 있다. 이 지시어는 콤마-구분자 리스트의 앞첨자(prefix)를 포함한다. 안전 모드에서, 유저는 여기서 제공되는 앞첨자로 시작하는 이름을 갖는 환경변수만 변경할수 있을것이다. 기본값으로, 유저는 PHP_로 시작하는 환경 변수만 설정할수 있다. (e.g. PHP_FOO=BAR).

Note: 이 지시어가 비어있으면, PHP는 유저가 모든 환경 변수를 변경할수 없게 할것이다!

safe_mode_protected_env_vars string

이 지시어는 엔드 유저가 putenv()를 사용하여 변경할수 없는 콤마-구분자 리스트의 환경 변수를 포함한다. 이 변수들은 safe_mode_allowed_env_vars가 그들을 변경할수 있도록 설정되어있을지라도 보호될것이다.

open_basedir string

PHP가 열수 있는 파일을 특정 디렉토리-트리로 제한한다. 이 지시어는 안전 모드가 켜졌는지 꺼졌는지와는 상관이 없다.

스크립트가 예를 들면, fopen() 이나 gzopen()으로 파일을 열려고 시도할때, 파일의 위치를 검사한다. 파일이 설정된 디렉토리-트리의 밖에 있다면, PHP는 그 파일을 여는것을 거부할것이다. 모든 심볼릭 링크가 검사되기 때문에, symlink로 이 제한을 회피할수 없다.

특수한 값 .은 스크립트가 작업하는 디렉토리를 기본 디렉토리로 사용합니다. 이는 스크립트의 작업 디렉토리가 chdir()을 통해 쉽게 바뀔 수 있기 때문에 조금 위험합니다.

윈도우에서는 세미콜른으로 디렉토리를 구분한다. 그외 모든 시스템은, 콜른으로 디렉토리를 구분한다. 아파치 모듈에서, 부모 디렉토리부터의 open_basedir 경로는 현재 자동적으로 상속된다.

open_basedir로 설정된 제한은 실질적으로 디렉토리명이 아닌, 앞첨자(prefix)가 된다. 이 말의 의미는 "open_basedir = /dir/incl"는 "/dir/include" 과 "/dir/incls" 디렉토리가 존재한다면 그 두 디렉토리로의 접근도 허용한다는것이다. 특정 디렉토리로만 접근을 제한하고자 한다면, 슬래쉬로 끝내면 된다. For example: "open_basedir = /dir/incl/"

Note: 다중 디렉토리에 대한 지원은 3.0.7에서 추가되었다.

기본값은 모든 파일이 열릴수 있도록 허용되어 있다.

disable_functions string
이 지시어는 보안 때문에 특정 함수를 비활성화시켜준다. 컴마로 구분된 함수명의 리스트를 취한다. disable_functions는 안전 모드에 의해 영향을 받지 않는다. 이 지시어는 php.ini에서 설정되어야 한다. 예를 들면, 이 값을 httpd.conf에서 설정할수 없다.
disable_classes string
이 지시어는 보안적인 측면때문에 특정 클래스를 비활성화시켜준다. 컴마로 구분된 클래스명의 리스트를 취한다. disable_classes는 안전 모드에 의해 영향을 받지 않는다. 이 지시어는 php.ini에서 설정되어야 한다. 예를 들면, 이 값을 httpd.conf에서 설정할수 없다.

Note: Availability note 이 지시어는 PHP 4.3.2부터 사용가능하게 되었다.

참고: register_globals, display_errors, log_errors

safe_mode가 켜져 있으면, PHP는 현재 스크립트의 소유자(owner)가 파일 함수에 의해 제어되는 파일의 소유자(owner)와 일치하는지 검사한다. 예를 들면:

-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 
이 script.php를 실행
<?php
 readfile
('/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 예):

<Directory /docroot>
  php_admin_value open_basedir /docroot 
</Directory>
open_basedir 설정으로 동일한 script.php를 실행하면 결과는 다음과 같다:
Warning: open_basedir restriction in effect. File is in wrong directory in 
/docroot/script.php on line 2 

또한 각각의 함수들을 비활성화시킬수 있다. disable_functions 지시어는 php.ini 파일 밖에서 사용될수 없다. 그래서 httpd.conf 파일의 per-virtualhost 나 per-directory 기반의 함수를 비활성화시킬수 없다. 이 지시어를 php.ini에 추가하면:

disable_functions readfile,system  
다음의 결과가 나온다:
Warning: readfile() has been disabled for security reasons in 
/docroot/script.php on line 2 



add a note add a note User Contributed Notes
안전 모드
Anonymous
19-Aug-2008 10:09
If you do it right, you dont have to use safemode on iis.

Running as an anonymous user will make it possible to restrict (on ntfs) access everywhere you dont want users/scripts to read from.
or the other way: permit access to the http-root-HDD (in my case) or directory and deny the rest.

wanting users not be able to access the other one's dir will either require you to use for every user another "website" or safemode (which is easier to do).

so based on your security needs you know what todo:P
Anonymous
23-Jan-2008 08:29
The location of the php.ini file is documented here:

http://www.php.net/manual/en/configuration.php

I agree that a hyperlink somewhere on the page would not be out of place.
scott at ahtenindustries dot com
16-Jan-2008 11:50
It would be nice if the documentation actually specified where the php.ini file is located.
15-Sep-2006 02:18
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.
martin at example dot com
01-Nov-2005 09:07
On the note of php security

have a look at: http://www.suphp.org/Home.html

 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.
hunter+phpnet at spysatcentral dot net
08-Aug-2005 02:25
I use mkdir just fine. You just have to make sure you set sticky bits on the directory you are creating the files in. Look at "man chmod" clipping:

4000    (the setuid bit).  Executable files with this bit set will run with effective uid set to the uid of the file owner. Directories with this bit set will force all files and sub-directories created in them to be owned by the directory owner and not by the uid of the creating process, if the underlying file system supports this feature: see chmod(2) and the suiddir option to mount(8).
mordae at mordae dot net
18-Jul-2005 11:19
It is possible to patch PHP/4 so it checks if just any directory in path is owned by proper user, e.g.
/home/mordae/www/dir/file
(where /home/mordae/www is mine and dir and file Apache's) will be readable if proper permissions set.
Read more at http://titov.net/safemodepatch/
jo at durchholz dot org
18-Jul-2005 05:18
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.
04-May-2005 01:37
To separate distinct open_basedir use : instead of on , or ; on unix machines.
plyrvt at mail dot ru
29-Apr-2005 07:14
[In reply to jedi at tstonramp dot com]
Safe mode is used "since the alternatives at the web server and OS levels aren't very realistic". Manual says about UNIX OS level and UNIX web-servers by design (Apache). It's not realistic for unix-like server, but for NT (IIS) each virtual host can run from different user account, so there is no need in Safe Mode restrictions at all, if proper NTFS rights are set.
bertrand dot gorge at epistema dot com
23-Sep-2004 09:58
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.
Russ
01-Sep-2004 12:52
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:

<?php
// Check for safe mode
if( ini_get('safe_mode') ){
   
// Do it the safe mode way
}else{
   
// Do it the regular way
}

?>
daniel dot gaddis at tlc dot state dot tx dot us
18-Mar-2004 04:03
on windows if multiple directories are wanted for safe_mode_exec_dir and open_basedir be sure to separate the paths with a semi colon and double quote the whole path string. For example:

safe_mode = On
safe_mode_exec_dir = "F:\WWW\HTML;F:\batfiles\batch"
open_basedir = "F:\WWW\HTML;F:\batfiles\batch"
uuganbat at datacom dot mn
26-Feb-2004 06:32
users executing shell scripts by filename.php, and I take the server in safe mode but some things are not working on web server, and disabled functions by php.ini but the simple commands in Unix are executing how  disable to execute shell scripts via *.php file.

example
<?php
echo `ls -l /etc/`; echo `more /etc/passwd`;
?>
matthias at remove-this dot hrz dot uni-kassel dot de
13-Nov-2003 02:38
Beware: Safe mode will not permit you to create new files in directories which have different owner than the owner of the script. This typically applies to /tmp, so contrary to Unix intuition, you will not be able to create new files there (even if the /tmp rights are set correctly).

If you need to write into files in /tmp (for example to put logfiles of your PHP application there) create them first on the command line by doing a

touch /tmp/whatever.log

as the same user who owns the PHP script. Then, provided the rest is configured correctly, the PHP script will be able to write into that file.
info at phpcoding dot net
08-Mar-2003 11:44
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.
gtg782a at mail dot gatech dot edu
27-Jan-2003 02:14
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.
dizzy at roedu dot net
17-Jan-2003 04:25
For people using linux there is a very nice solution to the shared server problem. It's called vserver/ctx. Here is the URL: http://www.solucorp.qc.ca/miscprj/s_context.hc
10-Sep-2002 07:30
Some paranoid web managers also restrict the set_user_abort() function.

This constitutes a security issue for hosted web sites, because the hosted script cannot guarantee safe atomic operations on files in a reasonnable time (the time limit may still be in effect):

If set_user_abort() is disabled by the web admin, a user can corrupt the files of a hosted web site by simply sending many requests to the PHP script, and aborting it fast. In some cases that can be easily reproduced after a dozen of attempts, the script will be interrupted in the middle of a file or database update!

The only way for the hosted web site to protect itself in this case is to use a sleep() with a random but not null short time before performing atomic operations.

Web admins should then definitely NOT disable the set_user_abort() function which is vital to ensure atomic operations on hosted critical files or databases.

Instead they should only disable the set_time_limit() function, and set a constant but reasonnable time for any script to complete their atomic operations.
10-Sep-2002 07:19
disk_free_space($directory) is also restricted by the safe_mode ! It can also be completely forbidden as this would allow a script to test the available space in order to fill it with a giant file, preventing other scripts to use that space (notably in "/tmp").
disk_free_space() is then informational, and this does not prevent system quotas to limit the size of your files to a value lower than the available free space!
Most web server admins that propose PHP hosting, will implement quotas for your hosting account, but also on any shared resources such as temporary folders.
tom at tom420 dot com
19-Jul-2002 05:33
open_basedir only restricts file operations to files and directories under a specified directory, but you can still user system ("vi /home/somedir/somefile"), so safe_mode still has a place here as it is much more restrictive then open_basedir.

Also, to reply to someone who said that 'above' and 'below' was a matter of perspective, sure it is. Of course, a file is not under another one, etc, it just pointed by some inode. But in the common language we consider the root (/) to be above everything else, and /home is below root, and /home/myfile is below /home. There is no written standard, but most people (those I know anyway) agree on that syntax.
zebz at ihaveenoughspam_hotmail dot com
29-Apr-2002 12:42
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.
devik at cdi dot cz
25-Jan-2002 09:45
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
jedi at tstonramp dot com
08-Sep-2001 11:17
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.

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