PHP 8.3.4 Released!

Datos Enviados por el Usuario

Las mayores debilidades de muchos programas PHP no son inherentes al lenguaje mismo, sino simplemente un problema generado cuando se escribe código sin pensar en la seguridad. Por esta razón, usted debería tomarse siempre el tiempo para considerar las implicaciones de cada pedazo de código, para averiguar el posible peligro involucrado cuando una variable inesperada es enviada.

Ejemplo #1 Uso Peligroso de Variables

<?php
// eliminar un archivo del directorio personal del usuario .. ¿o
// quizás de alguien más?

unlink ($variable_malvada);

// Imprimir el registro del acceso... ¿o quizás una entrada de /etc/passwd?
fwrite ($desc_archivo, $variable_malvada);

// Ejecutar algo trivial.. ¿o rm -rf *?
system ($variable_malvada);
exec ($variable_malvada);

?>

Usted debería examinar siempre, y cuidadosamente su código para asegurarse de que cualquier variable siendo enviada desde un navegador web sea chequeada apropiadamente, y preguntarse a sí mismo:

  • ¿Este script afectará únicamente los archivos que se pretende?
  • ¿Puede tomarse acción sobre datos inusuales o indeseados?
  • ¿Puede ser usado este script en formas malintencionadas?
  • ¿Puede ser usado en conjunto con otros scripts en forma negativa?
  • ¿Serán adecuadamente registradas las transacciones?

Al preguntarse adecuadamente estas preguntas mientras escribe su script, en lugar de hacerlo posteriormente, usted previene una desafortunada re-implementación del programa cuando desee incrementar el nivel de seguridad. Al comenzar con esta mentalidad, no garantizará la seguridad de su sistema, pero puede ayudar a mejorarla.

Puede que también desee considerar la deshabilitación de register_globals, magic_quotes, u otros parámetros convenientes que pueden causar confusión sobre la validez, fuente o valor de una determinada variable. Trabajar con PHP en modo error_reporting(E_ALL) también puede ayudarle a advertir variables que están siendo usadas antes de ser chequeadas o inicializadas (de modo que puede prevenir que datos inusuales produzcan operaciones inadvertidas).

add a note

User Contributed Notes 2 notes

up
78
Uli Kusterer
18 years ago
One thing I would repeat in the docs here is what information actually comes from the user. Many people think a Cookie, since it's written by PHP, was safe. But the fact is that it's stored on the user's computer, transferred by the user's browser, and thus very easy to manipulate.

So, it'd be handy to mention here again that:

CGI parameters in the URL, HTTP POST data and cookie variables are considered "user data" and thus need to be validated. Session data and SQL database contents only need to be validated if they came from untrustworthy sources (like the ones just mentioned).

Not new, but I would have expected this info under this headline, at least as a short recap plus linlk to the actual docs.
up
8
Livingstone@stonyhills[dot]com
16 years ago
making sure your form is submitted from your page! Could also be adapted to url, by additing &token to the query string and checking this against session data(or what ever array you like) with $_GET, not that this string is randomly generated and stored. If you like you could build your own array to store the generated string if you dont want to use $_SESSION, say you could make yours like $tokens = array(), and in your easysecure class you store all the stuff in that array!

<?php

class easysecure {

var
$curr_user;
var
$curr_permission;
var
$curr_task;
var
$validpermission;
var
$error;


function &
setVar( $name, $value=null ) {
if (!
is_null( $value )) {
$this->$name = $value;
}
return
$this->$name;
}

function
maketoken($formname, $id){

$token = md5(uniqid(rand(), true));

$_SESSION[$formname.$id] = $token;

return
$token;
}

function
checktoken($token, $formname, $id){
//print_r($_SESSION);
//echo ($token);
//if we dont have a valid token, return invalid;
if(!$token){
$this->setVar('validpermission', 0);
$this->setVar('error', 'no token found, security bridgedetected');
return
false;
}

//if we have a valid token check that is is valid
$key = $_SESSION[$formname.$id];
if(
$key !== $token ){
$this->setVar('validpermission', 0);
$this->setVar('error', 'invalid token');
return
false;
}

if(
$this->validpermission !==1){
echo
'invalid Permissions to run this script';
return
false;
}else{
return
true;
}
}

}

?>

<?php $userid = *** //make it what ever id you like ?>
<form name="newform" action="index.php" method="post">
<input type="text" name="potentialeveilfield" value="" size 30 />
<input type="hidden" name="token" value="<?php echo maketoken(newform, $userid); //$userid here could be user profile id ?>" />
<input type="submit" />
</form>

Now when processing the form... check the value of your token

<?php

//well you know the form name
if(!checktoken($_POST['token'], 'newform', $userid))
{
//failed
exit(); //or what ever termination and notification method best suits you.
//you could also design the class your way to get more accurate fail (error messages from the var)
}

//you can now continue with input data clean up (validation)

?>
To Top