How to block Chinese IP addresses in Phoenix Framework.

Sergio Tapia
sergiotapia
Published in
2 min readDec 20, 2017

--

Everyone has been in this situation at least once.

You’re relaxing, enjoying a nice afternoon working on a feature and suddenly you start seeing a bunch of traffic China doing all sorts of interesting things in your application.

Mitigation steps should be done at the web server level first and foremost. But sometimes that isn’t available to you — say if you’re hosted on Heroku.

If you do have access to your web server, you can use this handy list to configure your block list at the web server level. http://www.parkansky.com/china.htm

I’m going to show you how to block access at the code level, in your application.

What we’re going to use

  • plug_attack — this allows us to write a Plug that will allow specific connections.
  • ip2country — this will allow us to transform an IP octet into a country code. Nifty!
  • remote_ip — this automatically overwrites the conn.remote_ip with the value in the X-Forwarded-For header that places like Heroku uses. We need to know if someone came from China or not.

Add these packages to your mix.exs file and run mix deps.get.

{:plug_attack, "~> 0.3.0"},
{:ip2country, "~> 1.1"},
{:remote_ip, "~> 0.1.4"}

Create your Plug.

defmodule MyApp.Plug.PlugAttack do
import Plug.Conn
use PlugAttack

rule "deny china", conn do
ip_address = conn.remote_ip |> Tuple.to_list |> Enum.join(".")
allow IP2Country.whereis(ip_address) not in [:CN]
end
end

Add your Plug to your endpoint.ex file.

You want to ideally nuke the bad actor’s connection as fast as possible to make way for real customers.

Adding it to the endpoint.ex file before anything else, will mean that the conn is halted before any other step is taken. Perfect!

plug MyApp.Plug.PlugAttack

At this point you will be blocking Chinese IP addresses.

There’s one more step you need to take, making sure you get the remote_ip correctly.

Let’s just call the remote_ip plug right before our PlugAttack module.

plug RemoteIp
plug MyApp.Plug.PlugAttack

That’s all you need to do to block Chinese IP addresses in Phoenix Framework.

--

--