dismiss Step into the future! Click here to switch to the beta php.net site
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

Guillemets magiques> <Utilisation des variables super-globales
[edit] Last updated: Fri, 28 Jun 2013

view this page in

Données transmises par les internautes

La plus grande faiblesse de nombreux programmes PHP ne vient pas du langage en lui-même, mais de son utilisation en omettant les caractéristiques de sécurité. Pour cette raison, vous devriez toujours prendre le temps de réfléchir aux implications d'une portion de code donnée, pour mesurer les éventuels dommages qui pourraient être causés si une variable inattendue lui était passée.

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 variable envoyée par le client web qui ne soit pas suffisamment vérifiée avant utilisation, en vous posant les questions suivantes :

  • Est-ce que ce script n'affectera que les fichiers prévus ?
  • Est-il possible que des valeurs incohérentes ou inattendues soient exploitées ici ?
  • Est-ce que ce script peut être utilisé dans un but différent de celui attendu ?
  • Est-ce que ce script peut être utilisé malicieusement, en conjonction avec d'autres ?
  • Est-ce que toutes les actions seront correctement historisé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 lorsque vous aurez besoin d'améliorer leur 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 (register_globals), les guillemets magiques (magic_quotes), ou encore toute option qui pourrait conduire à vous tromper sur la validité, la source, ou la valeur d'une variable. Travailler avec PHP en mode error_reporting(E_ALL), peut aussi vous aider à détecter que certaines variables sont utilisées avant d'être exploitées ou initialisées (pour que vous puissiez empêcher l'utilisation de données inattendues).



add a note add a note User Contributed Notes Données transmises par les internautes - [3 notes]
up
3
Uli Kusterer
7 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
0
Livingstone@stonyhills[dot]com
5 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)

?>
up
-4
ffmandu13 at hotmail dot com
4 years ago
Hi,

Just one little class I made to control user's submitted datas, I thought it could help some people with security.
And if anyone wants to improve it, I'd be glad you do so.

<?php

/**
 * This program is under GNU GPL license.
 *
 * You can contact the author of this program at <ffmandu13@hotmail.com/>.
 */

//Defined regexps (you can add your own ones).
define('REG_DATE'          , '([[:digit:]]{4})-([[:digit:]]{2})-([[:digit:]]{2})');
define('REG_DIGIT_SIGNED'  , '^[-[:digit:]]+$');
define('REG_DIGIT_UNSIGNED', '^[[:digit:]]+$');
define('REG_PASSWORD'      , '^[[:alnum:]]+$');
define('REG_TEXT'          , '[[:graph:][:blank:]]+');
define('REG_WORD'          , '^[[:alpha:]]+$');

//Controls contents of the $_REQUEST variable.
final class checkVar{

  private
$tmp; //Secured value of a $_REQUEST key.

  //Check if the variable is set.
 
private function isSet(&$field){
    if(!isset(
$_REQUEST[$field]))
      throw new
Exception("You forgot to fill the $field field.");
    else
      return
true;
  }

 
//Set $tmp and remove threatening characters.
 
private function removeCharsThreats(&$field){
   
$this->tmp = trim($_REQUEST[$field]);
   
$this->tmp = htmlspecialchars($_REQUEST[$field], ENT_QUOTES, 'UTF-8', false); 
  }

 
//Checks if the value is equal to 1.
 
public function securityBool($field){
    if(
$this->isSet($field) && $_REQUEST[$field] != 1)
      throw new
Exception("Unallowed value in $field field.");
    else
      return
true;
  }

 
//Checks if the value is in the allowed ones list ($enum).
 
public function securityEnum($field, $enum){
    if(
$this->isSet($field)){
     
$this->removeCharsThreats($field);
     
$tab = explode(',', $enum);
      if(!
in_array($this->tmp, $tab))
        throw new
Exception("Unallowed value in $field field.");
      else
        return (string)
$this->tmp;
    }
  }

 
//Checks if the value is a numeric one and if it is in the given range.
 
public function securityRange($field, $range){
    if(
$this->isSet($field)){
     
$this->removeCharsThreats($field);
     
$tab = explode('/', $range);
      if(!
is_numeric($this->tmp))
        throw new
Exception("Unallowed characters in $field field.");
      elseif(
$this->tmp < $tab[0] || $this->tmp > $tab[1])
        throw new
Exception('Value must be in range '.$tab[0].'/'.$tab[1]." in $field field.");
      else
        return (int)
$this->tmp;
    }
  }

 
/**
   * Checks if the value respects the defined regexp,
   * and if its length is not superior than the given maxlength.
   */
 
public function securityText($field, $maxlength, $regexp){
    if(
$this->isSet($field)){
     
$this->removeCharsThreats($field);
      if(!
mb_ereg($regexp, $this->tmp))
        throw new
Exception("Unallowed characters in $field field.");
      elseif(
mb_strlen($this->tmp, ENCODING) > $maxlength)
        throw new
Exception("Too long string length for $field field.");
      else
        return
$this->tmp;
    }
  }

}

?>

Here are some examples of how to use the public methods.

<?php

$checkVar
= new checkVar();
$args     = array();

//If $_REQUEST['bbexport'] is not equal to 1, throws a new Exception.
$args['bbexport'] = $checkVar->securityBool('bbexport');

//If $_REQUEST['id'] is not an unsigned integer and/or has more than 4 digits, throws a new Exception.
$args['id']       = (int) $checkVar->securityText('id', 4, REG_DIGIT_UNSIGNED);

//If $_REQUEST['orderBy'] is not equal to 'date' or 'id' or 'name', throws a new Exception.
$args['orderBy']  = $checkVar->securityEnum('orderBy', 'date,id,name');

//If $_REQUEST['ratio'] is not a numeric value (integer or float) and is not between 0 and 10, throws a new Exception.
$args['ratio']    = $checkVar->securityRange('ratio', '0/10');

?>

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