How to validate the origin of the form?

Asked

Viewed 586 times

4

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

  • With a session id/token or captcha.

1 answer

3


There are different ways to do, the first and perhaps the most to 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>

This way you create a token and save it in the session, on the next page you check the POST and the session, if both have equal values means that the came from the same origin, this is a very basic example, there is still an example that tries to make it more difficult, in it all fields have random keys, follows 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 well that the use of HTTP_REFERER can often fail and can easily be cheated using plugin or requests by tools like CURL, wget, etc and even plugins for browsers can control the headers of the requests.

The anti-CRSF is considered much safer, but can also be cheated, however it is much more difficult to do this.

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

  • Thanks for the super explanatory answer, with the first solution the user can low form with key and send several times with trying to login, right?

  • @Cleideson can download the form with the key, but it is regenerated at any time, the key he downloads will be invalid when he tries to send a request via downloaded form ;)

  • 1

    Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.