How to create a GRE tunnel on Linux

A GRE (Generic Routing Encapsulation) tunnel is a way to provide a private path between networks. Commonly this is used with DDoS protection services. This works by setting up a GRE tunnel with the DDoS provider to your NodeSpace server. You then restrict access to your NodeSpace server from your DDoS protected IP.

You can setup a GRE tunnel between two Linux hosts. First, check that ip_gre kernel module is installed.

$ sudo modprobe ip_gre
$ lsmod | grep gre

If you see a response, you have ip_gre installed.

We're going to forward traffic through this tunnel using iptables and iproute2. You can install these with:

sudo yum install iptables iproute2

Now on the first server, enter the following:

sudo echo 'net.ipv4.ip_forward=1' >> /etc/sysctl.conf
sudo sysctl -p


Now create an interface for the tunnel.

sudo ip tunnel add gre1 mode gre local remote ttl 255
sudo ip addr add dev gre1
sudo ip link set gre1 up

Then on your NodeSpace server, do the same but change the IPs.

sudo ip tunnel add gre1 mode gre local remote ttl 255
sudo ip addr add dev gre1
sudo ip link set gre1 up


Add in a route on your NodeSpace server to make sure that anything that comes in via the GRE tunnel is routed correctly.

sudo echo '100 GRE' >> /etc/iproute2/rt_tables
sudo ip rule add from table GRE
sudo ip route add default via table GRE


On your first server, create the following NAT rule:

iptables -t nat -A POSTROUTING -s ! -o gre+ -j SNAT --to-source


This will pass data over the GRE tunnel and use the IP address of the first server. You can test this by running the following:

curl --interface


If you see your first server's IP and not your NodeSpace server's IP, then everything is working correctly.

Now we want to do some port forwarding so we send the right traffic over the GRE tunnel. On your first server, enter:

sudo iptables -A FORWARD -d -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A FORWARD -s -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT


And to forward specific ports, use this template for each port.

sudo iptables -t nat -A PREROUTING -d -p PROTO -m PROTO --dport PORT -j DNAT --to-destination


Replace PROTO and PORT with the appropriate protocol and port. For example, for HTTP port 80:

sudo iptables -t nat -A PREROUTING -d -p TCP -m TCP --dport 80 -j DNAT --to-destination


Then finally, we need to make these rules persist a reboot. To do this, edit /etc/rc.local and add all the commands entered, excluding any command that starts with "echo" before the line exit 0 in the file.

Article Details

Article ID:
Rating (Votes):

NodeSpace Hosting