How can I configure NAT on my VPC CIDR for traffic traversing a VPN connection?
Last updated: 2022-06-24
I have an AWS virtual private network (VPN) connection to a network or Amazon Virtual Private Cloud (Amazon VPC) where the network CIDRs overlap or I want to expose only a single IP. How do I configure network address translation (NAT) for my AWS VPN?
AWS VPN doesn't provide a managed option to apply NAT to VPN traffic. Instead, manually configure NAT using a software-based VPN solution. (There are many of these VPN solutions in the AWS Marketplace.) NAT can also be manually configured on the Amazon Elastic Compute Cloud (EC2) Linux instance that is running a software-based VPN solution along with iptables.
This example configuration uses two VPCs. The first is an AWS managed VPN and the second is a software-based VPN solution that is used as the customer gateway.
Before you begin, confirm that you set up an AWS Site-to-Site VPN connection. Then, install your selected VPN solution on the EC2 Linux instance by using your distribution's package manager.
Allow VPN traffic
Configure your VPC route table, security groups, and NACLs to allow VPN traffic:
- Enter the route towards the destination network into your route table. Set the elastic network interface of your software VPN EC2 instance as the target.
- Confirm that your route table has a default route with a target of an internet gateway.
- Allow inbound traffic using UDP port 500 (ISAKMP) and 4500 (IPsec NAT-Traversal) in the instance's security group rules.
- Turn off source/destination checks to allow the instance to forward IP packets.
Configure VPN connection
Configure the Site-to-Site VPN connection based on the solution that you chose. AWS offers downloadable example configuration files based on device vendor and model.
Configure your iptables rules for source NAT or destination NAT.
For source NAT, use the following string, filling in appropriate values in place of the brackets:
sudo iptables -t nat -A POSTROUTING -d <Destination address or CIDR> -j SNAT --to-source <Your desired IP address>
For destination NAT, use the following string, filling in appropriate values in place of the brackets:
sudo iptables -t nat -A PREROUTING -j DNAT --to-destination <Your desired IP address>
To save your running iptables configuration to a file, use this command:
sudo iptables-save > /etc/iptables.conf
To load this configuration on boot, place the following line in /etc/rc.local before the exit 0 statement:
iptables-restore < /etc/iptables.conf
Optional: Test your AWS Site-to-Site VPN connection. If the test is successful, the traffic is appropriately translated based on the iptables configuration.