Amazon VPC – How to Configure a Custom NAT

amazon ec2iptablesnat;

I have an Ubuntu box I wish to use as NAT instance (among other things). I would prefer to avoid using the NAT AMIs provided by Amazon, and instead configuring NAT myself.

Currently, my host has a single network interface (as shown in http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html ).

Should I be able to configure my Ubuntu host as the NAT instance for the other hosts in my Amazon network?

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
    pkts      bytes target     prot opt in     out     source               destination         
       5      454 MASQUERADE  all  --  *      eth0    0.0.0.0/0            0.0.0.0/0  

I tried configuring a NAT rule in the Ubuntu host (10.200.0.51). My second host is on a different network (10.200.10.41/24). So I wrote:

route add -net 10.200.0.0 netmask 255.255.255.0 dev eth0 # So I can reach 10.200.0.51
route add default gw 10.200.0.51

But the machine lost the connection.

What am I misunderstanding regading the usage of NAT instances and routing in Amazon?

Best Answer

You can check Amazon's script to configure NAT on a Linux machine, it comes with their default ami-vpc-nat AMI, in /usr/local/sbin/configure-pat.sh

It looks like this:

#!/bin/bash
# Configure the instance to run as a Port Address Translator (PAT) to provide 
# Internet connectivity to private instances. 

function log { logger -t "vpc" -- $1; }

function die {
    [ -n "$1" ] && log "$1"
    log "Configuration of PAT failed!"
    exit 1
}

# Sanitize PATH
PATH="/usr/sbin:/sbin:/usr/bin:/bin"

log "Determining the MAC address on eth0..."
ETH0_MAC=$(cat /sys/class/net/eth0/address) ||
    die "Unable to determine MAC address on eth0."
log "Found MAC ${ETH0_MAC} for eth0."

VPC_CIDR_URI="http://169.254.169.254/latest/meta-data/network/interfaces/macs/${ETH0_MAC}/vpc-ipv4-cidr-block"
log "Metadata location for vpc ipv4 range: ${VPC_CIDR_URI}"

VPC_CIDR_RANGE=$(curl --retry 3 --silent --fail ${VPC_CIDR_URI})
if [ $? -ne 0 ]; then
   log "Unable to retrive VPC CIDR range from meta-data, using 0.0.0.0/0 instead. PAT may be insecure!"
   VPC_CIDR_RANGE="0.0.0.0/0"
else
   log "Retrieved VPC CIDR range ${VPC_CIDR_RANGE} from meta-data."
fi

log "Enabling PAT..."
sysctl -q -w net.ipv4.ip_forward=1 net.ipv4.conf.eth0.send_redirects=0 && (
   iptables -t nat -C POSTROUTING -o eth0 -s ${VPC_CIDR_RANGE} -j MASQUERADE 2> /dev/null ||
   iptables -t nat -A POSTROUTING -o eth0 -s ${VPC_CIDR_RANGE} -j MASQUERADE ) ||
       die

sysctl net.ipv4.ip_forward net.ipv4.conf.eth0.send_redirects | log
iptables -n -t nat -L POSTROUTING | log

log "Configuration of PAT complete."
exit 0