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.
Seguridad del sistema de archivos
PHP está sujeto a la seguridad misma de la mayoría de sistemas de servidores en lo que a permisos sobre archivos y directorios se refiere. Esto le permite controlar cuáles archivos en el sistema de archivos pueden ser leídos. Debe tenerse cuidado con aquellos archivos que tengan permisos de lectura globales, para asegurarse de que su contenido es seguro y no represente peligro el que pueda ser leído por todos los usuarios con acceso al sistema de archivos.
Ya que PHP fue diseñado para permitir acceso al nivel de usuarios al sistema de archivos, es completamente posible escribir un script PHP que le permita leer archivos del sistema como /etc/passwd, modificar sus conexiones tipo ethernet, enviar trabajos de impresión masivos, etc. Esto tiene algunas implicaciones obvias, en el sentido en que usted tiene que asegurarse de que los archivos desde lo que lee y hacia los que escribe datos, sean los correctos.
Considere el siguiente script, en donde un usuario indica que quisiera eliminar un archivo ubicado en su directorio personal. Este caso asume que se trata de una situación en donde se usa normalmente una interfaz web que se vale de PHP para la gestión de archivos, así que el usuario de Apache tiene permitido eliminar archivos en los directorios personales de los usuarios.
Example #1 Un chequeo pobre de variables nos lleva a...
<?php
// eliminar un archivo del directorio personal del usuario
$nombre_usuario = $_POST['nombre_enviado_por_el_usuario'];
$archivo_usuario = $_POST['archivo_enviado_por_el_usuario'];
$directorio_home = "/home/$nombre_usuario";
unlink("$directorio_home/$archivo_usuario");
echo "¡El archivo ha sido eliminado!";
?>
Example #2 ... un ataque al sistema de archivos
<?php
// elimina un archivo de cualquier parte del disco duro al que el
// usuario de PHP tiene acceso. Si PHP tiene acceso de root:
$nombre_usuario = $_POST['nombre_enviado_por_el_usuario']; // "../etc"
$archivo_usuario = $_POST['archivo_enviado_por_el_usuario']; // "passwd"
$directorio_home = "/home/$nombre_usuario"; // "/home/../etc"
unlink("$directiorio_home/$archivo_usuario"); // "/home/../etc/passwd"
echo "¡El archivo ha sido eliminado!";
?>
- Otorgarle únicamente permisos limitados al usuario web del binario PHP.
- Chequear todas las variables que son enviadas por usuarios.
Example #3 Un chequeo de nombres de archivos más seguro
<?php
// elimina un archivo de cualquier parte del disco duro al que el
// usuario de PHP tiene acceso.
$nombre_usuario = $_SERVER['REMOTE_USER']; // uso de un mecanismo de autenticación
$archivo_usuario = basename($_POST['archivo_enviado_por_el_usuario']);
$directorio_home = "/home/$nombre_usuario";
$ruta_archivo = "$directorio_home/$archivo_usuario";
if (file_exists($ruta_archivo) && unlink($ruta_archivo)) {
$cadena_registro = "Se eliminó $ruta_archivo\n";
} else {
$cadena_registro = "No se pudo eliminar $ruta_archivo\n";
}
$da = fopen("/home/logging/eliminacion_archivos.log", "a");
fwrite($da, $cadena_registro);
fclose($da);
echo htmlentities($cadena_registro, ENT_QUOTES);
?>
Example #4 Chequeo de nombres de archivos aun más seguro
<?php
$nombre_usuario = $_SERVER['REMOTE_USER']; // uso de un mecanismo de autenticación
$archivo_usuario = $_POST['archivo_enviado_por_el_usuario'];
$directorio_home = "/home/$nombre_usuario";
$ruta_archivo = "$directorio_home/$archivo_usuario";
if (!ctype_alnum($nombre_usuario) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $archivo_usuario)) {
die("Nombre de usuario o archivo incorrecto");
}
//etc...
?>
Dependiendo de su sistema operativo, existe una amplia variedad de archivos sobre los que usted debería estar atento, incluyendo las entradas de dispositivos (/dev/ o COM1), archivos de configuración (archivos /etc/ y los archivos .ini), areas conocidas de almacenamiento de datos (/home/, Mis Documentos), etc. Por esta razón, usualmente es más sencillo crear una política en donde se prohíba toda transacción excepto por aquellas que usted permita explícitamente.
Problemas relacionados con bytes nulos
Dado que PHP usa las funciones de C de bajo nivel para las operaciones relacionadas con el sistema de archivos, puede que los bytes nulos sean gestionados de una forma inesperada. Debido a que los bytes nulos denotan el final de una cadena en C, las cadenas que los contienen no serán consideradas en su totalidad, sino únicamente hasta que ocurre un byte nulo. El siguiente ejemplo muestra un segmento de código vulnerable que demuestra este problema:
Example #5 Script vulnerable a bytes nulos
<?php
$archivo = $_GET['archivo']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$archivo.'.php')) {
// file_exists devolverá true ya que el archivo /home/wwwrun/../../etc/passwd existe
include '/home/wwwrun/'.$archivo.'.php';
// el archivo /etc/passwd será incluido
}
?>
Por lo tanto, cualquier cadena que sea usada en una operación del sistema de archivos debe ser validada apropiadamente siempre. He aquí una versión mejor del ejemplo anterior:
Example #6 Validación correcta de la entrada
<?php
$archivo = $_GET['archivo'];
// Lista de valores correctos posibles
switch ($archivo) {
case 'principal':
case 'foo':
case 'bar':
include '/home/wwwrun/include/'.$archivo.'.php';
break;
default:
include '/home/wwwrun/include/principal.php';
}
?>
Seguridad del sistema de archivos
27-Mar-2008 06:20
17-Apr-2007 04: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
17-Nov-2005 05: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.");
}
09-Oct-2005 07: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.
01-Sep-2005 12: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 ?>
23-Jun-2005 08: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.
10-Dec-2004 05: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.
06-May-2004 12: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
30-Mar-2002 07: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
05-Jan-2002 06: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
21-Aug-2001 10: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
11-Nov-2000 12: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.
:-)
