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

search for in the

Guillemets magiques> <Utilisation des variables super-globales
Last updated: Fri, 20 Jun 2008

view this page in

Données transmises par les internautes

Les plus grandes faiblesses de nombreux programmes PHP ne viennent pas du langage lui-même, mais de son utilisation en omettant les caractéristiques de sécurité. Pour cette raison, vous devez toujours prendre le temps de prendre en compte les implications d'une fonction, et de cerner toutes les applications d'une utilisation exotiques des paramètres.

Exemple #1 Utilisation dangereuse de variables

<?php
// efface un fichier à la racine d'un utilisateur... ou peut être
// de quelqu'un d'autre?
unlink($evil_var);
// Note l'accès de ce fichier ... ou pas?
fputs($fp$evil_var);
// Exécute une commande triviale... ou ajoute une entrée dans /etc/password ?
system($evil_var);
exec($evil_var);
?>

Il est vivement recommandé d'examiner minutieusement votre code pour vous assurer qu'il n'y a pas de variables envoyées par le client web, et qui ne sont pas suffisamment vérifiées avant utilisation.

  • Est-ce que ce script n'affectera que les fichiers prévus?
  • Est-il possible que des valeurs incohérentes soient exploitées ici?
  • Est-ce que ce script peut être utilisé dans un but différent?
  • Est-ce que ce script peut être utilisé malicieusement, en conjonction avec d'autres?
  • Est-ce que toutes les actions seront notées?

En répondant de manière adéquate à ces questions lors de l'écriture de vos scripts (plutôt qu'après), vous éviterez une réécriture inopportune pour raison de sécurité. En commençant vos projets avec ces recommandations en tête, vous ne garantirez pas la sécurité de votre système, mais vous contribuerez à l'améliorer.

Vous pouvez aussi envisager de supprimer l'acquisition automatique des variables d'environnement, les guillemets magiques (magic_quotes), ou encore toute option qui pourrait vous conduire à vous tromper sur la validité, la source ou la valeur d'une variable. En travaillant avec error_reporting(E_ALL), vous pouvez être averti que certaines variables sont utilisées avant d'être exploitées, ou vérifiées (et donc, vous pourrez traiter des valeurs exotiques à la source).



add a note add a note User Contributed Notes
Données transmises par les internautes
Viz
13-Jun-2008 01:47
@f dot zijlstra

Actually you should not filter against known bad data, you need to white list your filters. Rather than looking for bad data, you should strip everything but what you expect because it's future proof.

example for a 32 character text input field:
$inputvar=substr(htmlentities($_POST['inputvar']),0,32);
$inputvar=preg_replace('/[^\w\.\-\& ]/', '', $inputvar);

This will strip numbers, newlines, null characters, # and all non-printable characters, only allowing word characters(determined by locale setting), .,-, space and &, as well as truncate the value to the size you accept. You could use preg_match instead and throw an error if there's anything outside the pattern.

This can be a little painful because you might miss a character you need, and have to add it to your code, but it's easier than restoring your database, or explaining to your customers about why their data is now in the hands of identity thieves.

Default deny for the long term win. It's the only security panacea that works now and always will. Blacklists are the completely wrong approach because they don't handle future threats you don't know about yet.

Further you should use mysqli and prepared statements for queries which use user data as parameters, after using the mysql filters on the input data. If you really want to go the extra mile, start using stored procedures because it will allow you to remove SELECT, DELETE, UPDATE and INSERT permissions from the web server user. All you need is EXECUTE for stored procs, thereby limiting what can be seen of the database to only the functions you expose(and you can easily expose too much if you aren't careful).

Naturally the big dangers are SQL injection and XSS. A simple filter like this will break them when combined with a prepared statement.

As someone else noted, relying on _anything_ from the client is an extremely bad idea because it can all be spoofed (including HTTP_REFERER) using Paros, Tamper Data or any other client side proxy, by doing a simple man in the middle tamper on yourself.

You can make HTTP_REFERER=http://www.whitehouse.gov if you want.

Sorry to segway into db security, but you can't avoid it when talking about sanitizing input which leads to building queries.

-Viz
f dot zijlstra at gmail dot com
18-May-2008 09:07
I'd like to note that the 'easysecure' thing posted below is NOT a secure way to validate that the form was indeed submitted from a browser. In fact, there is NO way you can guarantee that.

A smart person with bad intentions can easily parse the HTML page to fetch the generated token and pass it on. The only way to secure your forms is to explicitly check every variable against potentially dangerous values.
Livingstone@stonyhills[dot]com
02-Feb-2008 08:51
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)

?>
Uli Kusterer
13-Sep-2005 06:50
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.

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