Saturday, January 09, 2016

AWS EC2 - How to create prerouting in iptables

OS: "Amazon Linux AMI release 2015.09"

By using iptables and its masquerade feature, it is possible to forward traffic from one source to another destination. But create PREROUTING rule in AWS EC2 could be tricky. Here are the steps how I did it on my server:

Start iptables service
By default, service iptables is not running, you can check its status by:
# service iptables status
iptables: Firewall is not running.

Try to start the process I got:
# service iptables start
# service iptables status
iptables: Firewall is not running.

You need to manually create "/etc/sysconfig/iptables" in order to get it running:
# touch /etc/sysconfig/iptables
# service iptables start
# service iptables start
iptables: Applying firewall rules:                         [  OK  ]

Once you have your iptable service running, create a POSTROUTING rule first:
# iptables -t nat -A POSTROUTING -j MASQUERADE

Then create your PREROUTING rule:
# iptables -t nat -A PREROUTING -p tcp -s my_ip --dport 3000 -j DNAT --to-destination new_server_ip:80

This way, all the traffics from "my_ip", to port "3000" will be redirected to "new_server_ip:80"

Of course, you need to enable "ipv4_forwarding"
# echo "1" > /proc/sys/net/ipv4/ip_forward
# vim /etc/sysctl.conf
change
net.ipv4.ip_forward = 0
to
net.ipv4.ip_forward = 1

Hope this helps.

No comments: