Jump to content

How to block IP's from some Countries ?


irigsoft

Recommended Posts

  • Replies 66
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Posted Images

38 minutes ago, Norm said:

I was responding to Frederick's question regarding VPN hacks. He is making a valid point that hackers can break through your IP lookup solution by connecting to your server using their own VPNs to pretend they are in your country.

The only way to avoid VPN hacks is to gradually build up a list of allowed IP's.

yes , If I use VPN then that will be best practices I will use. thank You

Link to comment
Share on other sites

1 hour ago, Norm said:

Once you have completed your solution would you mind sharing because I'm very interested.

 

Yes,

I wait @Sherzod to analized situation.

At this moment I try, but XMLHttpRequest dont show any message, and MainForm.onAjax dont fire.:

procedure TUniMainModule.UniGUIMainModuleCreate(Sender: TObject);
    function  getIPDetails (sRemIP: String): String;
   var
  sRemoteCountry      : String;
  begin
  TRY
      UniSession.AddJS  ('  new Promise(function(resolve, reject) {' +
                        ' const xhttp = new XMLHttpRequest();'

//                        + ' xhttp.onreadystatechange = function () {'
//                        + '   if (this.readyState == 4 && this.status == 200) {'
//                        + '          alert (getIPDetails 1);'
//                        + '          var sRes = xhttp.responseText;'
//                        + '          Form_General.ajaxRequest (Form_General'
//                        + '                        , "getIPDetails", ["_country=" + "" + sRes.country + "","_countrycode=" + " + sRes.country + "]);'
                        //+ '        console.log(JSON.parse(xhttp.responseText));'
                        //+ ' let params= JSON.parse(xhttp.responseText);'//JSON.stringify(params);
                        //+ ' ajaxRequest(top.frmLogin.htmlFrame, 'scountry',['countryname='+ params.country])
                        //+ ' alert (params.country);'
//                        + '    };'
//                        + '};'
                        + ' xhttp.open("GET", "http://ip-api.io/json/'  + sRemIP + '",true);'
                        + ' xhttp.send(null);'
                        + ' var sRes = xhttp.responseText;'
                        + ' if (sRes != "") {'
                        + '            alert (getIPDetails 2);'//alert (sRes.country);
                        + '            MainForm.ajaxRequest (MainForm'
                        + '                        , "getIPDetails", ["_country=" + "" + sRes.country + "","_countrycode=" + " + sRes.country + "]);'
                        + ' };' //if sRes <> ''

                        + '}'
                        );

      Result := sCountry;
  EXCEPT
      on E:Exception do showmessage (e.Message);
  END;
  end;

begin

//first check IP Country
IF AnsiUpperCase (getIPDetails (uniSession.RemoteIP)) <> AnsiUpperCase (uniServerModule.MainSettings.Values ['RqstCountryCode']) then begin
    uniSession.AResponse.ContentText := '<h1>Access denied</h1>';
    unIServerModule.BlockedIPList.Add (uniSession.RemoteIP);
    unIServerModule.BlockedIPList.SaveToFile (ExtractFilePath(unIServerModule.StartPath) + '\MyConfigList.ini');
    uniSession.CloseSession;
    exit;
end;

end;

 

procedure TMainForm.UniFormAjaxEvent(Sender: TComponent; EventName: string;   Params: TUniStrings);
begin
 if EventName = 'getIPDetails' then begin
  uniMainModule.sCountry := Params['_countrycode'].value;
end;

end;

 

 

Link to comment
Share on other sites

1 hour ago, irigsoft said:

OK, how do You thing, what is prottection from this ?

I am not sure if there is a solution for this. Some web sites attempt to block me based on the country I am from, while I am using a VPN, and it annoys me no end.

If you are able to block users based on their IP addresses, while they are using a VPN, I would be interested to see how you succeeded.

Link to comment
Share on other sites

1 minute ago, Frederick said:

I am not sure if there is a solution for this. Some web sites attempt to block me based on the country I am from, while I am using a VPN, and it annoys me no end.

If you are able to block users based on their IP addresses, while they are using a VPN, I would be interested to see how you succeeded.

At the moment I do not intend to use VPN, but if necessary and find a solution, I will share it here.

Link to comment
Share on other sites

16 minutes ago, irigsoft said:

At the moment I do not intend to use VPN, but if necessary and find a solution, I will share it here.

@Frederick,I tried the API and found that local IP addresses do not receive Country information. If the client uses a VPN, I thing a local IP address will be generated and the api will not work.

Link to comment
Share on other sites

This is my solution:

This checks every request in UniGUIServerModuleHTTPCommand and I'm not sure if using it in mainModule.OnCreate will not be better. 

I dont know what can do attacker before session creation, so I am prefer to use it in UniGUIServerModuleHTTPCommand.

If I can make the check stop when the session is open, it will be fine.

I am open to suggestions.

uses   URLMon, WinINet

procedure TUniServerModule.UniGUIServerModuleHTTPCommand(  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo;   var Handled: Boolean);

function  getIPDetails (sRemIP: String): String;
var
sRemoteCountry      : TStringList;
begin
sRemoteCountry := TStringList.Create;
sRemoteCountry.StrictDelimiter := True;
sRemoteCountry.Delimiter := ',';
TRY

if not FileExists (YourLocationPath + '\CountriesData\' + sRemIP + '_Ctry.txt') then begin
  uniServerModule.sysDownloadURL ('http://ip-api.io/json/'  + sRemIP,YourLocationPath + '\CountriesData\' + sRemIP + '_Ctry.txt');
end;
if FileExists (YourLocationPath + '\CountriesData\' + sRemIP + '_Ctry.txt') then begin
    sRemoteCountry.LoadFromFile(YourLocationPath + '\CountriesData\' + sRemIP + '_Ctry.txt');
    Result := sRemoteCountry.Text;
    Result := StringReplace (Result,':','=',[rfReplaceAll]);
    Result := StringReplace (Result,'{','',[rfReplaceAll]);
    Result := StringReplace (Result,'}','',[rfReplaceAll]);
    Result := StringReplace (Result,'"','',[rfReplaceAll]);

    //parse json answer

    sRemoteCountry.DelimitedText := Result;
    sCountry := TRIM (sRemoteCountry.Values['country_code']);

    Result := TRIM (sRemoteCountry.Values['country_code']);

    //if there not errors
    if TRIM (sRemoteCountry.Values ['status_code']) <> '404' then begin
        //if Country is not in settings
        if AnsiUpperCase (SistemSettingsList.Values ['RqstCountryID']) <> AnsiUpperCase (sCountry)

//and they are not into ExcepIpList - Stringlist with All trusted IP 's

AND (uniServerModule.TrustedIpList.IndexOf (sRemIP) <= 0)

then
            save in BlockedIPLIst;
    end;
end;

EXCEPT
      on E:Exception do showmessage (e.Message);
END;
sRemoteCountry.Clear;
sRemoteCountry.Free;
end;

begin

//Check Country, if not in settings, then close session

IF AnsiUpperCase (getIPDetails (ARequestInfo.RemoteIP)) <> AnsiUpperCase (SistemSettingsList.Values ['RqstCountryID'])) 

//and they are not into WhiteLIst

AND (uniServerModule.TrustedIpList.IndexOf (ARequestInfo.RemoteIP) <= 0)

then begin
    AResponseInfo.ContentText := '<h1>Access denied</h1>';
    Handled := True;
    AResponseInfo.CloseSession;
    exit;
end;
end;

 

//download json answer from API to file. I am save in file to not check every time with API (there is limit of free usage)

function TUniServerModule.sysDownloadURL (aUrl,DestFile: AnsiString): Boolean;
var
sInt    : Integer;
begin
try
    //clear cash
    DeleteUrlCacheEntry (PChar(aUrl));
    sInt := URLDownloadToFile (nil, PChar(aUrl), PChar(DestFile), 0, nil);
    Result := sInt = 0;
except
    on E:Exception do begin
        Result := False;
    end;
end;
end;
 

Link to comment
Share on other sites

7 minutes ago, Frederick said:

That is what the VPN is supposed to do; mask my actual country of origin.

I know that VPN uses encrypted communication. It is possible to mask a country, but if you use a VPN client on my VPN server, it will ask for your credentials.

So I accept your warning, but at this point I will consider the VPN secure.

Any local IP will be ignored by this security check.

There are other security restrictions on my server (StandAloneApplication).

 

Link to comment
Share on other sites

Can you please explain what you mean by this:

I tried the API and found that local IP addresses do not receive Country information. If the client uses a VPN, I thing a local IP address will be generated and the api will not work.

What do you mean by "local IP address"?

VPN's do not hide country information, they replace it with the target country.

Link to comment
Share on other sites

10 hours ago, Norm said:

Can you please explain what you mean by this:

I tried the API and found that local IP addresses do not receive Country information. If the client uses a VPN, I thing a local IP address will be generated and the api will not work.

What do you mean by "local IP address"?

VPN's do not hide country information, they replace it with the target country.

I test api with my IP 127.0.0.1 like this: http://ip-api.io/json/127.0.0.1 and API return answer in json, {"status_message":"Not found","status_code": 404}

So when You use IP from local network and want to check Country, then You will get this json answer with error. So When use VPN , what is IP of Client.

If I use in my VPN server IP (local network): 192.168.23.111 (external IP: 124.45.XXX.XX), and You connect with Your VPN Client, what will be Your IP in this VPN network (192.168...... or 124.45.....)?

I thing You will get 192.168.23.XXX

So when You try to connect to uniGuiApplication via VPN what will be Your IP then, i think 192.168.23.XXX, in that way API will return error in json as answer

 

as @Frederick says : "If you travel, a VPN can give you access to geoblocked websites and streaming content from your home country (even you local Netflix library) while you're away. A few select VPNs can even keep you connected to all your favorite websites while you're visiting countries with strict censorship policies, like China or Russia."

Link to comment
Share on other sites

Now I understand!

You are right. Local IP is not linked to any country, that is why the IP Lookup service will return 404.

However, this has nothing to do with VPN. When somebody uses a VPN to connect to your server the IP that your server will see is the external IP of the VPN, not the users local IP. The reason people use VPN to connect to any international site is to hide their own external IP. For example, I am in New Zealand and sometimes I want to connect to a UK football site. If I don't use a VPN the UK site will refuse my connection because the service is only for UK residents. So I use a VPN service and select UK as my required target country. The VPN will route my connection to their own UK server and from there I can connect to the football site. When the server of the football site checks my IP what they will see is the external IP of the VPN service in the UK instead of my New Zealand external IP so they will allow my connection.

I hope that makes sense.

Link to comment
Share on other sites

2 minutes ago, Norm said:

Now I understand!

You are right. Local IP is not linked to any country, that is why the IP Lookup service will return 404.

However, this has nothing to do with VPN. When somebody uses a VPN to connect to your server the IP that your server will see is the external IP of the VPN, not the users local IP. The reason people use VPN to connect to any international site is to hide their own external IP. For example, I am in New Zealand and sometimes I want to connect to a UK football site. If I don't use a VPN the UK will refuse my connection because the service is only for UK residents. So I use a VPN service and select UK as my required target country. The VPN will route my connection to their own UK server and from there I can connect to the football site. When the server of the football site checks my IP what they will see is the external IP of the VPN service in the UK instead of my New Zealand external IP so they will allow my connection.

I hope that makes sense.

"The reason people use VPN to connect to any international site is to hide their own external IP" - Please can you explain to me how you will connect to a VPN, where will you get a user / pass pass? Is there a way to connect to a VPN as anonymous?

"For example, I am in New Zealand and sometimes I want to connect to a UK football site. If I don't use a VPN the UK will refuse my connection because the service is only for UK residents."  - what VPN server will you use? maybe you will connect to a VPN server in the UK, from a VPN client in New Zealand and then connect to this UK football site?

I'm not familiar with VPN, I know it uses a secure connection and several methods to connect client and server

Please explain to me how your New Zealand VPN client can connect to the UK football site, if this site does not have a VPN server, is there a way?

I'm studying a VPN because I accept your comments.

I understand that the use of VPN allows for the concealment of state information, but the WhiteIPlist can still be used.
My system is not a website in the sense of Magento, Prestashop, etc. and in most cases will be used by users in one country. But here the methods are applied together:
1. WhiteIPList
2. IP Range
3. BlockedIPList

Link to comment
Share on other sites

I pay an annual fee for a VPN service called ExpressVPN. It is a very good service. Whenever I want to connect to the UK football site I start the VPN app and it asks me which country I want. The app then connects to the ExpressVPN server in the UK (they have servers in most counties). So when I type the URL of the football site the VPN app routes my connection through their UK server.

Link to comment
Share on other sites

36 minutes ago, Norm said:

I pay an annual fee for a VPN service called ExpressVPN. It is a very good service. Whenever I want to connect to the UK football site I start the VPN app and it asks me which country I want. The app then connects to the ExpressVPN server in the UK (they have servers in most counties). So when I type the URL of the football site the VPN app routes my connection through their UK server.

Yes, I mean just that.

You need to connect to your VPN server.

In this ExpressVPN you can connect your client to a VPN server and then you will connect to this football site.

So far, I've made a remote-access VPN between NAS routers, between Windows computers, and everyone required me to create a server first and then log in between a client and a server.

You're talking about a Site-to-Site VPN, but I'm not familiar with that.

Can't figure out how you can connect from your VPN client (with a changed country) to my site in my country without having a VPN server in my country?
As far as I understand, the only thing that happens is that your VPN Client receives some "external" IP (fake), which will be presented to my site as if it were from my country, because you know which is my country.

 

If I have located the site in UK, but I have indicated that I will only accept clients from the USA, how will you understand this?

Link to comment
Share on other sites

OK, lets go back to your situation.

What you are trying to do is to only allow connections within your own country. You don't need a VPN to do that. All you have to do is to check incoming connection (via the IP Lookup server) to see which country the connection is coming from. For example, if your neighbor tried to connect to your unigui app the app will see his external IP, not his local IP. So the lookup service will confirm that the connection came from your country.  So no VPN issues here.

Now about VPN's. This is where Frederick came in.

If I tried to connect to you app from New Zealand, the IP Lookup service will tell you that I am not in your country so you will block my connection. However if I start my VPN and tell it that I want to pretend that I am in your country, the ExpressVPN app will route my connection through their own server in your country (as I said they have servers in most countries). So the IP address your unigui app will see is that of the ExpressVPN server in your country. As Frederick was indicating, this is how I can bypass IP blocking mechanism.

My suggestion to you is to completely forget about VPNs in your security design solution. Why would anybody go through the trouble of configuring a VPN just so they can try and hack your app when there is no monetary reward for them.

 

 

Link to comment
Share on other sites

A different approach could be using Cloudflare. They have a free version tot test with. After the setup it is very easy to make all kinds of rules. You have all kind of options. 

With Cloudflare you can get a lot of benefits regarding security, speed/caching e.g. 

image.thumb.png.a23c9e92a5e1e9d8a865ed3495b6d817.png

Link to comment
Share on other sites

10 minutes ago, Norm said:

What you are trying to do is to only allow connections within your own country. You don't need a VPN to do that. All you have to do is to check incoming connection (via the IP Lookup server) to see which country the connection is coming from. For example, if your neighbor tried to connect to your unigui app the app will see his external IP, not his local IP. So the lookup service will confirm that the connection came from your country.  So no VPN issues here.

Yes, that is.

11 minutes ago, Norm said:

f I tried to connect to you app from New Zealand, the IP Lookup service will tell you that I am not in your country so you will block my connection. However if I start my VPN and tell it that I want to pretend that I am in your country, the ExpressVPN app will route my connection through their own server in your country (as I said they have servers in most countries). So the IP address your unigui app will see is that of the ExpressVPN server in your country. As Frederick was indicating, this is how I can bypass IP blocking mechanism.

To understand. In this case, it is better to position my server in the United Kingdom and accept only a user from Germany. Maybe this will confuse hackers?

12 minutes ago, Norm said:

My suggestion to you is to completely forget about VPNs in your security design solution. Why would anybody go through the trouble of configuring a VPN just so they can try and hack your app when there is no monetary reward for them.

I don't know what information my clients can use / store, but I have to protect them from various default attacks (according to laws like the GDPR, US law, and so on).

Clients can always use different security tools for their security and I would recommend it to all my clients, but I want to integrate some familiar protections into my uniGui server, especially since I'm not behind IIS, Apche or anything else.

Link to comment
Share on other sites

1 hour ago, Norm said:

I'm sorry but I think Frederick is a little confused about how VPN's work. There no way a VPN can be seen by any international site as a local IP.

 

The international site will see the IP address as coming from that country where the international site is located. So, in your case, the UK web site thinks that you are in UK when you are in New Zealand. It is because your ExpressVPN is connecting to its VPN server in UK which then redirects your URL call to the UK football web site.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...