How to validate form's origin?

4

I have a web application in which there is a login and registration form, and from what I realized I can download the HTML from my site and send the request through my PC pointing to the site, so how do I check the origin of the form?

    
asked by anonymous 20.03.2016 / 03:08

1 answer

3

There are different ways to do it, the first and perhaps the most use is the "anti-CRSF" (if you can call it that):

authenticate.php:

<?php
session_start();

if (isset($_POST['token'], $_POST['login'], $_POST['senha'])) {
    $token = empty($_SESSION['token']) ? NULL : $_SESSION['token'];

    //Compara o token com o post
    if ($_POST['token'] === $token) {
         /*Valida $_POST['login'] e $_POST['senha']*/
    } else {
         echo 'Requisição invalida';
    }
} else {
    echo 'Faltam dados no Form';
}

login.php

<?php
session_start();

//Cria um token
$_SESSION['token'] = md5(uniqid(rand(), true));
?>

<form method="POST" action="autenticar.php">
<input type="hidden" name="token" value="<? php echo $_SESSION['token']?>" />
<input type="text" name="login" placeholder="login"><br>
<input type="password" name="senha" placeholder="senha"><br>
<button type="submit">Logar</button>
</form>

In this way you create a token and save it to the session, the next page you check the POST and the session, if both have equal values means that the same origin, this is a very basic example, there is still an example which tries to make it even harder, in it all fields have random keys, follow the example:

The other way is to check the referer, for example:

  • http://exemplo/paginaA.php

    <form method="POST" action="paginaB.php">
    <input type="text" name="login" placeholder="login"><br>
    <input type="password" name="senha" placeholder="senha"><br>
    <button type="submit">Logar</button>
    </form>
    
  • http://exemplo/paginaB.php

    <?php
    if (empty($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] !== 'http://exemplo/paginaA.php') {
        echo 'Acesso bloqueado';
        exit;
    }
    
    //Resto do script
    

Note that using HTTP_REFERER can often crash and can easily be cheated using plugin or requests by tools such as CURL, wget, etc. and even browser plugins can control the headers of requests.

Anti-CRSF is considered much more secure, but it can also be cheated, however it is much more difficult to do this.

In short, there is nothing 100% safe, but examples help prevent it.

    
20.03.2016 / 03:21