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

search for in the

Database Security> <Instalace jako modul do Apache
Last updated: Sat, 24 Mar 2007

view this page in

Kapitola 26. Bezpečnost souborových systémů

PHP pracuje se zabezpečením zabudovaným do většiny serverových systémů, které je založeno na oprávněních k souborům a adresářům. To vám umožňuje ovládat, které soubory v souborovém systému se smí číst. Pozornost je potřeba věnovat jakýmkoli souborům, které jsou čitelné všem uživatelům, kvůli tomu, zda je skutečně bezpečné, aby je směli číst všichni uživatelé, kteří mají k tomuto systému přístup.

Jelikož je PHP navrženo tak, aby umožňovalo přístup k filesystému na úrovni uživatele, je vcelku možné napsat PHP skript, který vám umožní číst systémové soubory, jako např. /etc/passwd, měnit konfiguraci ethernetu, posílat na tiskárnu obrovské tiskové úlohy apod. To má jasné důsledky v tom, že se musíte vždy ujistit, že soubory, které chcete číst nebo zapisovat, jsou skutečně ty správné.

Uvažujme následující skript, kde uživatel říká, že by chtěl smazat soubor ve svém domovském adresáři. To předpokládá situaci, kde se pro normální správu souborů používá webové rozhraní implementované pomocí PHP, a uživatel, pod nímž běží Apache, má právo mazat soubory v domovských adresářích uživatelů.

Příklad 26.1. Slabá kontrola proměnných vede k....

<?php
// odstraň soubor z domovského adresáře uživatele
$username = $_POST['user_submitted_name'];
$homedir = "/home/$username";
$file_to_delete = "$userfile";
unlink ("$homedir/$userfile");
echo
"$file_to_delete byl smazán!";
?>

Jelikož se uživatelské jméno posílá z formuláře, může kdokoli poslat uživatelské jméno a soubor patřící někomu jinému a mazat cizí soubory. V takovém případě byste měli chtít používat nějakou formu autentizace. Uvažte, co by se mohlo stát, kdyby poslané proměnné obsahovaly "../etc/" a "passwd". Kód by pak mohl bez problémů číst:

Příklad 26.2. ...útoku na souborový systém

<?php
// Odstraní soubor odkudkoli na pevném disku, kam má uživatel PHP přístup.
// Má-li PHP rootovská práva:
$username = "../etc/";
$homedir = "/home/../etc/";
$file_to_delete = "passwd";
unlink ("/home/../etc/passwd");
echo
"/home/../etc/passwd byl smazán!";
?>

Existují dvě důležité roviny, ve kterých byste se měli těmto problémům bránit.
  • Povolit programu PHP pouze omezená oprávnění.
  • Kontrolovat všechny zasílané proměnné.
Zde je vylepšený skript:

Příklad 26.3. Bezpečnější kontrola názvu souboru

<?php
// Odstraní soubor z pevného disku, kam má uživatel PHP přístup.
$username = $_SERVER['REMOTE_USER']; // použití autentizačního mechanismu

$homedir = "/home/$username";

$file_to_delete = basename("$userfile"); // odřízni cestu
unlink ($homedir/$file_to_delete);

$fp = fopen("/home/logging/filedelete.log","+a"); // zaznamenej smazání
$logstring = "$username $homedir $file_to_delete";
fwrite ($fp, $logstring);
fclose($fp);

echo
"$file_to_delete byl smazán!";
?>

Ovšem ani toto není zcela neprůstřelné. Pokud by váš autentizační systém povoloval uživatelům vytvářet si vlastní uživatelská jména, a uživatel by si vybral "../etc/", systém by byl opět ohrožen. Z tohoto důvodu byste měli preferovat lépe přizpůsobenou kontrolu:

Příklad 26.4. Bezpečnější kontrola názvu souboru

<?php
$username
= $_SERVER['REMOTE_USER']; // použití autentizačního mechanismu
$homedir = "/home/$username";

if (!
ereg('^[^./][^/]*$', $userfile))
     die(
'bad filename'); // skonči, nezpracovávej

if (!ereg('^[^./][^/]*$', $username))
     die(
'bad username'); // skonči, nezpracovávej
// atd...
?>

V závislosti na operačním systému existuje celá široká škála souborů, o které bychom se měli zajímat, včetně souborů zařízení (/dev/ nebo COM1), konfiguračních souborů (soubory /etc/ a .ini), známé oblasti ukládání souborů (/home/, Dokumenty) atd. Proto je obvykle lepší ustanovit politiku, kde je zakázáno všechno kromě toho, co explicitně povolíte.



Database Security> <Instalace jako modul do Apache
Last updated: Sat, 24 Mar 2007
 
add a note add a note User Contributed Notes
Bezpečnost souborových systémů
BAT Svensson
27-Mar-2008 03:20
A note on mapping for added security.

The principle with mapping is: WHAT YOU SEE MAY NOT BE.

Map each entity that can be manipulated to a token. Only the token will be displayed to the end user. For added security, map allowed functionality to each token. Changing the token will at most cause a user to manipulate some else already mapped file. This achieve the goal of control and limited access.

There is a variety to implement this but the main point here is that a physical name should never be displayed to the end user, thus restricting an evil user knowledge of the system and it architecture.

This principle is also know under names such as "black box" or "need to know" or "abstraction", etc etc depending on the context.

The point here is that one does not need to know under lying structure in order to do operation one high levels such as "add/move/remove/edit". Present a view - the view will provide the user with what the user need to know.

It is all about creating an illusion of existence at higher level of something that does not exist on a lover level.
steelchords at yahoo dot com
17-Apr-2007 01:12
It seems to me in this particular instance that a simple check to make sure that name or partial pathname doesn't already exist would prevent this attack... if a 'passwd/etc/...' existed as the password directory, you couldn't create a username to exploit the hole in the first place.  But that's only from a 'script user' perspective, it still doesn't protect your server from other sub-admin's badly written code.

Don For
anonymous
17-Nov-2005 02:58
(A) Better not to create files or folders with user-supplied names. If you do not validate enough, you can have trouble. Instead create files and folders with randomly generated names like fg3754jk3h and store the username and this file or folder name in a table named, say, user_objects. This will ensure that whatever the user may type, the command going to the shell will contain values from a specific set only and no mischief can be done.

(B) The same applies to commands executed based on an operation that the user chooses. Better not to allow any part of the user's input to go to the command that you will execute. Instead, keep a fixed set of commands and based on what the user has input, and run those only.

For example,
(A) Keep a table named, say, user_objects with values like:
username|chosen_name   |actual_name|file_or_dir
--------|--------------|-----------|-----------
jdoe    |trekphotos    |m5fg767h67 |D
jdoe    |notes.txt     |nm4b6jh756 |F
tim1997 |_imp_ folder  |45jkh64j56 |D

and always use the actual_name in the filesystem operations rather than the user supplied names.

(B)
<?php
$op
= $_POST['op'];//after a lot of validations
$dir = $_POST['dirname'];//after a lot of validations or maybe you can use technique (A)
switch($op){
    case
"cd":
       
chdir($dir);
        break;
    case
"rd":
       
rmdir($dir);
        break;
    .....
    default:
       
mail("webmaster@example.com", "Mischief", $_SERVER['REMOTE_ADDR']." is probably attempting an attack.");
}
fmrose at ncsu dot edu
09-Oct-2005 04:31
All of the fixes here assume that it is necessary to allow the user to enter system sensitive information to begin with. The proper way to handle this would be to provide something like a numbered list of files to perform an unlink action on and then the chooses the matching number. There is no way for the user to specify a clever attack circumventing whatever pattern matching filename exclusion syntax that you may have.

Anytime you have a security issue, the proper behaviour is to deny all then allow specific instances, not allow all and restrict. For the simple reason that you may not think of every possible restriction.
joshudson';DROP TABLE EMAILS;' gmail.com
01-Sep-2005 09:50
I keep application configuration files in the document root. I found the most effective trick to prevent access to them is to
1. Give them no code that actually runs when included (except for variable assignments),
2. Don't use register globals so nobody can do anything weird,
3. Name them *.php so PHP runs them when asked for
4. Don't have anything before <?php
5. Don
't have a ?>
1 at 234 dot cx
23-Jun-2005 05:24
I don't think the filename validation solution from Jones at partykel is complete.  It certainly helps, but it doesn't address the case where the user is able to create a symlink pointing from his home directory to the root.  He might then ask to unlink "foo/etc/passwd" which would be in his home directory, except that foo is a symlink pointing to /.

Personally I wouldn't feel confident that any solution to this problem would keep my system secure.  Running PHP as root (or some equivalent which can unlink files in all users' home directories) is asking for trouble.

If you have a multi-user system and you are afraid that users may install scripts like this, try security-enhanced Linux.  It won't give total protection, but it at least makes sure that an insecure user script can only affect files which the web server is meant to have access to.  Whatever script someone installs, outsiders are not going to be able to read your password file---or remove it.
Jones at partykel dot de
10-Dec-2004 02:00
What about:

<?php
  $file_to_delete
= '/home/'.$username.'/'.$userfile;
 
  if ((!
ereg('\.\.', $file_to_delete)) and (file_exists($file_to_delete))) {
     
unlink($file_to_delete);
  }
?>

I think this should prevent every attempt to go outside the user-directory.
Additionally you should check usernames at the registration.

Another way whould be to use the user-ID as home-directory - so, this can't be changed and every registered user as an unique one (if it's a primary key in your database). But then you still have to check the given $userfile.

So the code above could be taken as a "last instance check" directly before finally deleting of the file.
akul at inbox dot ru
06-May-2004 09:59
Common and simple way to avoid path attack is separating objectname and filesystem space when possible. For example if I have users on my site and directory per user solution is not "httpdocs/users/$login", but "httpdocs/users/".md5($login) or "httpdocs/users/".$userId
tim at correctclick dot com
30-Mar-2002 04:48
One more thing --

whenever you connect to a database with a password hard coded into your script, make sure you put the script off of your web document tree.  Put the script somewhere where apache won't serve documents, and then include/require this file in your other scripts.  That way, if the server ever gets misconfigured, it won't serve your PHP scripts with passwords, etc. as plain text for all to see.

-Tim
cronos586(AT)caramail(DOT)com
05-Jan-2002 03:48
when using Apache you might consider a apache_lookup_uri on the path, to discover the real path, regardless of any directory trickery.
then, look at the prefix, and compare with a list of allowed prefixes.
for example, my source.php for my website includes:
if(isset($doc)) {
    $apacheres = apache_lookup_uri($doc);
    $really = realpath($apacheres->filename);
    if(substr($really, 0, strlen($DOCUMENT_ROOT)) == $DOCUMENT_ROOT) {
        if(is_file($really)) {
            show_source($really);
        }
    }
}
hope this helps
regards,
KAT44
devik at cdi dot cz
21-Aug-2001 07:52
Well, the fact that all users run under the same UID is a big problem. Userspace  security hacks (ala safe_mode) should not be substitution for proper kernel level security checks/accounting.
Good news: Apache 2 allows you to assign UIDs for different vhosts.
devik
eLuddite at not dot a dot real dot addressnsky dot ru
11-Nov-2000 09:44
I think the lesson is clear:

(1) Forbit path separators in usernames.
(2) map username to a physical home directory - /home/username is fine
(3) read the home directory
(4) present only results of (3) as an option for deletion.

I have discovered a marvelous method of doing the above in php but this submission box is too small to contain it.

:-)

Database Security> <Instalace jako modul do Apache
Last updated: Sat, 24 Mar 2007
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites