Control of login attempts by PHP

Asked

Viewed 1,162 times

0

I need to provide an external access for a small reporting system, however, I do not know how to control login attempts since I will have to validate the access using the user table of a third-party software, so I can not change the tables.

As the use of cookies is not indicated and also could not implement reCaptcha with internal access. In this case there is some kind of control that can be applied in this situation using only PHP?

  • I prefer to capture the IP and put it in a log file. Session in an instant the user clear the browser history all gets lost.

  • Will checking this log file not slow down? About the session, this applies also in brute force?

  • Laravel has such a system. They use a cache system, combined with information sent to Http Header. Each time he takes the previous Header value and adds +1.

  • Do you talk about a server-side cache? That sounds interesting. I’ll search the PHP documentation. Thank you!

2 answers

2


Can use SESSION.

For each attempt, increment a variable in $_SESSION and also record the time the guy tried. If you’ve had more than this many attempts in the last hour or so.

  • 1

    I ended up focusing so many on the solutions already presented by the community that I ended up ignoring the existence of SESSION. Thanks for the tip.

  • Then the guy cleans the browser cookie, and it can "start from scratch" again, right. That’s the only flaw of this method. Use Session and use Cookie gives in it. The session depends on the Cookie to work.

0

Follow a complete implementation with number of attempts and reCaptcha I’m using on a site I’m developing, the only thing missing to work 100% is to create the objects, but I left well described how to create them, I’m just a student so I did the best I could.

<?php ini_set('display_errors',1); ini_set('display_startup_erros',1); error_reporting(E_ALL); ?><!--Força o php a mostrar todo tipo de erro, linha temporária-->
    <?php
    function __autoload($class_name){
        require_once '../_lib/'.$class_name.'.php';//-->lê minhas classes de forma automática
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" type="text/css" href="_css/login.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script src='https://www.google.com/recaptcha/api.js'></script>
        <script>
            $(document).ready(function() {
                $('#send').prop('disabled', true);//desativa o botão enviar
                $('.g-recaptcha').hide();//esconde o captcha
                validate();
                $('#inputEmail, #inputPassword').change(validate);
            });
            function validate() {
                if ($('#inputEmail').val().length > 10) {//enquanto o campo de email nao tiver menos que 10 caracteres, não ativa o reCaptcha
                    $('.g-recaptcha').show();//exibe o reCaptcha
                }else{//se mudar de ideia e reduzir o campo pra menos de 10 caracteres...
                    $('.g-recaptcha').hide();//o reCaptcha se esconde novmanete
                }
            }
            function enableSend() {
                $('#send').prop('disabled', false);//quando o captcha é confirmado, ativa o botao enviar
            }
        </script>
    </head>

    <body>
    <?php
    $helper = new Helpers();//-->objeto com vários métodos importantes
    if (isset($_POST['attempt'])){//verifica se tem tentativa restante
        $attempt = intval($helper->validation($_POST['attempt']));//validation=método que verifica e escapa minha sring (trim(), stripcslashes() e htmlspecialchars())
    }else{
        $attempt = 3;//se não for definido número de tentativas, aqui é definido como 3
    }

    if (isset($_POST['g-recaptcha-response']) and isset($_POST['username']) and isset($_POST['password'])) {//garante que todos os campos foram preenchidos
        $captcha_data = $_POST['g-recaptcha-response'];
        if ($captcha_data) {//Verificação do reCaptcha
            $resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=DIGITE-SUA-CHAVE-SECRETA-GERADA-PELO-GOOGLE-AQUI=" . $captcha_data . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
            if ($resposta) {//validação do reCaptcha
                $username = strtolower($helper->validation($_POST['username']));
                $password = $helper->validation($_POST['password']);
                $user = new User();//--->meu objeto que acessa o banco de dados usando PDO
                $userValidated = $user->checkPasswordHash($username);//--->método do meu objeto que procura o usuario no bacno de dados (SELECT * FROM tbl_Users WHERE username = $username)
                if ($userValidated){//verifica se o email existe, se existir...
                    if ($userValidated->status == 1){//verifica se a conta está bloqueada ou não
                        echo 'Essa conta está bloqueada, criar botão para reenviar o email de recuperação...';
                    }else{
                    $hash = $userValidated->password;//retorna o hash do password
                    if (password_verify($password, $hash)) {//compara a senha e o hash que foi criado usando password_hash() e salvo no banco de dados
                        echo 'Password é válido, inserir código que inicia as sessões e chama a próxima página';//-->insira seu código
                    } else {//caso o password estjeja errado, perde uma tentativa
                        if ($attempt != 1){//se a tentativa restante for igual a 1, a proxima vez será direcionado para a página de recuperação de senha
                            $attempt--;
                            echo 'Usuário e senha não combinam, você tem mais '.$attempt.' tentativas';//mostra o número de tentativas restante
                        }else{//bloqueia a conta e chama a página de recuperação de senha
                            echo 'inserir código que bloqueia a conta e abre pagina de recuperaçao de senha';//-->insira seu código de bloqueio
                        }
                    }
                    }
                }else{//se o email não existir, perde uma tentativa mas não avisa se o erro foi no email ou na senha
                    if ($attempt != 0){
                        $attempt--;
                        echo 'Usuário e senha não combinam, você tem mais '.$attempt.' tentativas';//mostra o número de tentativas restante
                    }else{//bloqueia a conta e chama a página de recuperação de senha
                        echo 'inserir código que bloqueia a conta e abre pagina de recuperaçao de senha';//-->insira seu código de bloqueio
                    }
                }
            } else {
                echo "Validação não concluída, tente novamente.";
                exit;
            }
        } else {
            echo "Validação não concluída, tente novamente.";
            exit;
        }
    }
    ?>
    <section>
        <form class="login" action="login.php" method="post">
            <fieldset>
                <legend>Login</legend>
                <label for="inputEmail" class="Label">Email: </label>
                <input id="inputEmail" class="inputText" type="email" maxlength="30" name="username" required>
                <label for="inputPassword" class="Label">Password: </label>
                <input id="inputPassword" class="inputPassword" type="password" maxlength="20" name="password" required>
                <div class="g-recaptcha" data-sitekey="DIGITE-A-CHAVE-DO-SEU-SITE-CRIADA-PELO-GOOGLE-AQUI" data-callback="enableSend"></div><!--Linha que adiciona o recaptcha-->
                <input type="hidden" name="attempt" value=<?php echo $attempt ?> /><!--envia por post o numero de tentativas restante-->
                <input type="submit" value="Confirmar" id="send" class="send">
            </fieldset>
        </form>
    </section>

    </body>
    </html>

Browser other questions tagged

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