Block user access with foreign IP's

2

Is it possible to restrict access to a particular site or Web system, so that only Brazilian IP's can access it?

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

With this IP information at hand, I would then create a table in MySql, and then perform the access validation in PHP.

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

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

Now, what I would really like is to implement this IP validation.

    
asked by anonymous 15.05.2018 / 03:59

2 answers

2

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

I will use generic names for the file naming, but I did it with the help of the GEOIP API, so I just created the PHP and MySQL part, which I hope will be useful for you.

Before, you need to register to receive your token via email: link

After this, just change the lines of the files 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>

process.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 should only save the code of the desired country in your database. The system will compare what is saved and will block access. Just run a "BR" test on your database. Insert in the DB and do something like this after pulling the data:

Let's say that the variable "country"

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

Is it something you want?

    
15.05.2018 / 04:22
2

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

  • 1 - Get Ip visitor $ipaddress = $_SERVER['REMOTE_ADDR'];
  • 2 - transform Ip into long ip $ipno = sprintf('%u', ip2long($ipaddress));
  • 3 - Select countrySHORT according to long ip $query = "SELECT countrySHORT FROM tbl_ipcountry WHERE ".$ipno." BETWEEN ipFROM AND ipTO";
  • 4 - Compare the returned value, if% with 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 a dot notation is 120.121.5.123.

     

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

    
15.05.2018 / 08:03