Block user access with foreign IP’s

Asked

Viewed 1,148 times

2

It is possible to restrict access to a particular website or Web system, so that only IP’s in Brazil can access it?

I have a mini-system in PHP, and to further increase its security, I would like to make it inaccessible for all kinds of foreign access. At first, I thought about setting up some specific IP(s) (s) track(s) from foreign countries, so that any access from this parameter would be blocked.

With this IP information in hand, you would then create a table in Mysql, and then perform access validation in PHP.

Even if it is not possible to map all necessary IP tracks, just deleting something will already contribute to the security of the system.

Already 'Blindei' my application to prevent attacks of type XSS and SQL Injection, etc. I also implemented several security validations.

Now, what I’d really like to do is implement this IP validation.

  • Have geoip API. Read about?

  • I’ll read it. Thanks Alex.

  • i decided to respond with a project I have here. I hope it will be useful somehow.

2 answers

3


Well, I had the same problem a while ago, but I managed to join the solution of an API with some own solutions in PHP, nothing extraordinary, after all, it is the API that does everything practically.

I will use generic names for file appointments, but I managed with the help of the GEOIP API, then just create the PHP and Mysql part, which I hope will be useful for you.

before, you need to register to receive your token via email: https://www.localizaip.com.br/api_localiza_ip.php

After this, just change the file lines correctly.

index php.

<script language="javascript">
var LIP_LowPrecision = false; //false = ask permission to the browser, higher precision | true = don't ask permission, lower precision
function LocalizaIP_done(ip_data){
    if (!ip_data['error']) //this line is an exemple, you must change it by your Geolocation manipulation code
        var pais = ip_data["countryCode"];

        $.ajax({
            data: 'pais=' + pais,
            url: 'processa.php',
            method: 'POST', // or GET
            success: function(msg) {
                //alert(msg);

                if(msg == 'banido'){
                    window.location="http://meusite.com.br/404/";
                }
            }
        });
}
</script>

<script src="https://www.localizaip.com/api/geolocation.js.php?domain=meusite.com.br&token=MEU_TOKEN=="></script>

parses.php

<?php
    $hostname_conexao = "localhost";
    $username_conexao = "root";
    $password_conexao = "";
    $database_conexao = "teste";

    $mysqli = new mysqli($hostname_conexao, $username_conexao, $password_conexao, $database_conexao);

    if ($mysqli->connect_errno)
    {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    $pais = $_POST['pais'];

    $query  = "SELECT pais FROM banirips WHERE pais='".$pais."'";

    if($stmt_count = $mysqli->query($query))
    {
        $count_results = $stmt_count->num_rows;
        $stmt_count->close();   
    }

    if($count_results >= 1){echo "banido";}
?>

banirips.sql

id | pais |
1  |  AR  |
2  |  BR  |

You must save only the code of the desired country in your database. The system will compare what is saved and will block access. Just do a test with "BR" in your database. Insert it in the BD and do something like that after pulling the data:

Let’s say the variable "country"

if($pais == 'BR')
{
echo "PAÍS BLOQUEADO!";
}
else
{
echo "PAÍS SEM RESTRIÇÃO DE ACESSO!";
}

It’s something you want?

  • exactly Alex! I will implement this structure in my system. Thanks for the help.

  • Arrange, my friend Good luck

  • -1. You are totally trusting the customer, he or she can manipulate the response of "www.localizaip.com" or else block the loading of "www.localizaip.com" content, which will then be able to access your site normally. Just like users who have JS disabled or who use the "read mode" of the browser, or even those who load the page and pause loading as soon as they see the content. This is totally foolproof with no need for proxies or vpn.

  • Knowing one tool, one has to know others, colleague. Nothing prevents him from studying some other API. I gave a solution to the answer to the question. Now if you want a complete XSS-proof system and all kinds of hacking, I don’t think that’s the right place. The Stack is not a deposit of systems. It is a place where one gives a direction and the way it makes is us.

  • And another, rep does not mean ;)

2

Yes, it is possible to restrict access to a particular website or web system, so that only ips from Brazil can access it. Required a table as shown in item 3 below.

  • 1 - Get the Ip of the visitor $ipaddress = $_SERVER['REMOTE_ADDR'];
  • 2 - transforms the Ip over ip $ipno = sprintf('%u', ip2long($ipaddress));
  • 3 - Select country acronym (countrySHORT) according to long ip $query = "SELECT countrySHORT FROM tbl_ipcountry WHERE ".$ipno." BETWEEN ipFROM AND ipTO"; tabela
  • 4 - Compare the returned value if BR free access.

PHP

//'** conexão com banco de dados
      $mysqli = new mysqli(....);

//'** Obtenção do Ip do visitante
    $ipaddress = $_SERVER['REMOTE_ADDR'];


//'** busca do país de origem da visita

    //transforma o ip em ip longo
    $ipno = sprintf('%u', ip2long($ipaddress));

    echo $ipno;

    //selecione a sigla do pais (countrySHORT) de acordo com o ip longo
    $query  = "SELECT countrySHORT FROM tbl_ipcountry WHERE ".$ipno." BETWEEN ipFROM AND ipTO";

        $result = mysqli_query($mysqli,$query);

        while($row = mysqli_fetch_assoc($result))
        {   
           $Nome_Pais = $row['countrySHORT'];
        }

    //se for diferente de BR direciona para
    if($Nome_Pais!="BR"){

       header('Location: http://dominio.com/404.php');

    }

ip2long ( $ip_address ) - converts an ASCII string containing a valid Internet address using dot notation (IP) into an integer (long IP). An example of dot notation is 120.121.5.123.

The function ip2long() becomes very useful, when it is necessary to store IP addresses in a database, reducing considerably the space used, besides making much faster a future query by these IP addresses. The space reduction is because instead of storing the IP address as a string - 121.122.123.124 - and using a char(15) field, which would take 15 bytes, you can store it as an integer - 2130706433 - and spend 4 bytes instead of 15 bytes.

  • Thanks Leo, I’ll take a look at it. Abçs.

  • Good alternative, Leo

Browser other questions tagged

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