Upcoming Critical PHP Security Release

Sicurezza del filesystem

Indice dei contenuti

PHP è soggetto alla sicurezza integrata nella maggior parte dei sistemi server per quanto riguarda i permessi su file e directory. Ciò consente di controllare quali file nel filesystem possono essere letti. Si dovrebbe prestare attenzione a tutti i file leggibili da chiunque, per garantire che possano essere letti in sicurezza da tutti gli utenti che hanno accesso a quel filesystem.

Poiché PHP è stato progettato per consentire l'accesso a livello utente al filesystem, è del tutto possibile scrivere uno script PHP che ti consenta di leggere file di sistema come /etc/passwd, modificare le connessioni ethernet, inviare enormi lavori di stampa, ecc. Questo ha alcune ovvie implicazioni, in quanto devi assicurarti che i file da cui leggi e su cui scrivi siano quelli appropriati.

Considera il seguente script, dove un utente indica che vorrebbe eliminare un file nella propria directory home. Ciò presuppone una situazione in cui un'interfaccia web PHP viene regolarmente utilizzata per la gestione dei file, quindi all'utente Apache è consentito eliminare i file nelle directory home degli utenti.

Example #1 Un controllo non accurato delle variabili porta a...

<?php

// Rimuove un file dalla directory home dell'utente
$username = $_POST['user_submitted_name'];
$userfile = $_POST['user_submitted_filename'];
$homedir  = "/home/$username";

unlink("$homedir/$userfile");

echo "The file has been deleted!";

?>
Poiché il nome utente e il nome del file possono essere inviati da un form, è possibile inviare un nome utente e un nome di file appartenenti a un altro utente, ed eliminarlo anche se non si dovrebbe essere autorizzati a farlo. In questo caso, dovresti usare un'altra forma di autenticazione. Considera cosa potrebbe accadere se le variabili inviate fossero "../etc/" e "passwd". In pratica, il codice diventerebbe:

Example #2 ... Un attacco al filesystem

<?php

// Rimuove un file da qualsiasi punto del disco rigido a cui
// l'utente PHP ha accesso. Se PHP ha accesso come root:
$username = $_POST['user_submitted_name']; // "../etc"
$userfile = $_POST['user_submitted_filename']; // "passwd"
$homedir  = "/home/$username"; // "/home/../etc"

unlink("$homedir/$userfile"); // "/home/../etc/passwd"

echo "The file has been deleted!";

?>
Ci sono due misure importanti che dovresti adottare per prevenire questi problemi.
  • Concedere solo permessi limitati all'utente web con cui viene eseguito il binario PHP.

  • Controllare tutte le variabili inviate.

Ecco uno script migliorato:

Example #3 Controllo più sicuro dei nomi dei file

<?php

// Rimuove un file dal disco rigido a cui
// l'utente PHP ha accesso.
$username = $_SERVER['REMOTE_USER']; // utilizzando un meccanismo di autenticazione
$userfile = basename($_POST['user_submitted_filename']);
$homedir  = "/home/$username";

$filepath = "$homedir/$userfile";

if (file_exists($filepath) && unlink($filepath)) {
    $logstring = "Deleted $filepath\n";
} else {
    $logstring = "Failed to delete $filepath\n";
}

$fp = fopen("/home/logging/filedelete.log", "a");
fwrite($fp, $logstring);
fclose($fp);

echo htmlentities($logstring, ENT_QUOTES);

?>
Tuttavia, anche questo non è privo di difetti. Se il tuo sistema di autenticazione consentisse agli utenti di creare i propri login, e un utente scegliesse il login "../etc/", il sistema sarebbe nuovamente esposto. Per questo motivo, potresti preferire scrivere un controllo più personalizzato:

Example #4 Controllo più sicuro dei nomi dei file

<?php

$username     = $_SERVER['REMOTE_USER']; // utilizzando un meccanismo di autenticazione
$userfile     = $_POST['user_submitted_filename'];
$homedir      = "/home/$username";

$filepath     = "$homedir/$userfile";

if (!ctype_alnum($username) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $userfile)) {
    die("Bad username/filename");
}

// ecc.

?>

A seconda del sistema operativo, esiste un'ampia varietà di file di cui dovresti preoccuparti, tra cui i file di dispositivo (/dev/ o COM1), i file di configurazione (file in /etc/ e file .ini), le aree di archiviazione dei file ben note (/home/, My Documents), ecc. Per questo motivo, di solito è più facile creare una policy in cui si proibisce tutto tranne ciò che viene consentito esplicitamente.

+add a note

User Contributed Notes 5 notes

up
100
anonymous
21 years ago
(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.");
}
up
23
fmrose at ncsu dot edu
21 years ago
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.
up
21
devik at cdi dot cz
25 years ago
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
up
10
Latchezar Tzvetkoff
17 years ago
A basic filename/directory/symlink checking may be done (and I personally do) via realpath() ...

<?php

if (isset($_GET['file'])) {
    $base = '/home/polizei/public_html/';  // it seems this one is good to be realpath too.. meaning not a symlinked path..
    if (strpos($file = realpath($base.$_GET['file']), $base) === 0 && is_file($file)) {
        unlink($file);
    } else {
        die('blah!');
    }
}
?>
up
2
cronos586(AT)caramail(DOT)com
24 years ago
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
To Top