phpday 2027 - Call for Papers

Dati inviati dall'utente

La più grande debolezza di molti programmi scritti in PHP non è insita nel linguaggio, ma è semplicemente un problema di codice scritto senza tenere a mente la sicurezza. Per questo motivo, bisognerebbe sempre prendersi il tempo di considerare le implicazioni di una certa parte di codice, per accertare il possibile danno se gli viene inviata una variabile inaspettata.

Example #1 Utilizzo pericoloso delle variabili

<?php
// rimuove un file dalla home directory dell'utente... o forse
// da quella di qualcun altro?
unlink ($evil_var);

// Scrive nel log il loro accesso... o magari una voce in /etc/passwd?
fwrite ($fp, $evil_var);

// Esegue qualcosa di banale.. o rm -rf *?
system ($evil_var);
exec ($evil_var);

?>

Bisognerebbe sempre esaminare attentamente il proprio codice per assicurarsi che tutte le variabili inviate da un browser web vengano correttamente controllate, e porsi le seguenti domande:

  • Questo script avrà effetto solo sui file previsti?

  • Lo script può operare su dati inusuali o indesiderati?

  • Questo script può essere utilizzato in modi non previsti?

  • Può essere usato insieme ad altri script in modo dannoso?

  • Le transazioni verranno adeguatamente tracciate?

Ponendosi queste domande durante la scrittura dello script, piuttosto che in seguito, si evita una spiacevole riscrittura quando si ha bisogno di migliorarne la sicurezza. Partendo con questa mentalità non si garantisce la sicurezza del sistema, ma si può contribuire a migliorarla.

Si può migliorare la sicurezza disabilitando le impostazioni di comodo che rendono poco chiari l'origine, la validità o l'integrità dei dati in input. La creazione implicita di variabili e l'input non verificato possono portare a vulnerabilità come attacchi di injection e manipolazione dei dati.

Funzionalità come register_globals e magic_quotes (entrambe rimosse in PHP 5.4.0) un tempo contribuivano a questi rischi creando automaticamente variabili dall'input dell'utente ed effettuando l'escape dei dati in modo incoerente. Sebbene non siano più presenti in PHP, rischi simili persistono se l'input viene gestito in modo errato.

Abilitare error_reporting(E_ALL) aiuta a rilevare le variabili non inizializzate e a convalidare l'input. Utilizzare la tipizzazione stretta (declare(strict_types=1), introdotta in PHP 7) per garantire la sicurezza dei tipi, prevenire conversioni di tipo involontarie e migliorare la sicurezza generale.

+add a note

User Contributed Notes 2 notes

up
80
Uli Kusterer
21 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
5
Livingstone@stonyhills[dot]com
18 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