The modern cloud infrastructure requires applications and services to communicate between different Virtual Private Clouds (VPCs) throughout multiple regions or accounts. Inter-VPC communication refers to the process of enabling secure and seamless data transfer between these isolated VPCs.
The functionality allows multi-region and multi-account organizations to enable safe resource interactions between different Virtual Private Clouds.
In the context of AWS EC2 instances, inter-VPC communication allows virtual machines in separate VPCs to communicate with each other over a private, encrypted network. This is crucial for applications that need high availability, disaster recovery, or regional redundancy.
Why Use Libreswan IPSec VPN Tunnel for Secure Communication Between AWS EC2 Instances?
Libreswan is a powerful and flexible open-source implementation of the IPSec protocol, which is widely used for creating secure Virtual Private Networks (VPNs). When setting up inter-VPC communication on AWS EC2 instances, Libreswan IPSec VPN tunnels provide a secure and encrypted way to connect VPCs in different regions or accounts.
Libreswan provides multiple benefits that surpass the capabilities of AWS Managed VPN and other tunneling methods through IPSec VPN. The VPN configuration receives complete management through the system which permits users to customize security policies and encryption protocols alongside routing rules.
Libreswan proves suitable as a VPN solution for users requiring adaptability and custom security alongside performance from their VPNs.
Overview of Benefits (Cost-Effectiveness, Security, Control)
- Cost-Effectiveness: Unlike AWS Managed VPN services, which incur ongoing monthly fees, Libreswan is open-source software, meaning no additional charges for software licensing. The only costs involved are those associated with the EC2 instances and data transfer, which is significantly more affordable for long-term usage, especially in multi-region setups.
- Security: IPSec ensures that data is encrypted end-to-end, protecting sensitive information from eavesdropping, tampering, and unauthorized access. Libreswan supports various strong encryption algorithms and security protocols, giving you full control over your encryption policies. This level of security is vital for organizations handling sensitive data across regions.
- Control: One of the most significant benefits of using Libreswan is the control it offers. Unlike AWS’s managed VPN solutions, which are pre-configured and limited in customization, Libreswan allows for detailed configuration of the VPN tunnel. You can fine-tune the tunnel’s settings to meet specific business and technical requirements, such as custom routing, advanced security settings, and more.
Step 1: Prerequisites
Successful configuration of Libreswan IPSec VPN tunnels requires you to fulfill these necessary conditions. Success of the VPN tunnel and secure connection between your AWS EC2 instances in distinct VPCs depends on the successful fulfillment of these important requirements.
Two AWS EC2 Instances in Separate VPCs (with Elastic IPs)
To establish a VPN tunnel between two AWS EC2 instances, you need:
- Two EC2 instances running in separate VPCs (Virtual Private Clouds). Each instance will be the endpoint of the IPSec VPN tunnel.
- Elastic IPs (EIPs) for both EC2 instances. These public IPs will serve as the source and destination for the tunnel traffic. Using EIPs ensures that the IP addresses remain static, which is important for maintaining a stable VPN connection. This is especially crucial if you’re working in a multi-region or multi-account setup.
Having these EC2 instances in different VPCs is what enables inter-VPC communication. The Elastic IPs make sure that each EC2 instance remains accessible even after instances are rebooted or stopped.
Basic Knowledge of Libreswan and IPSec
- Libreswan is an open-source IPSec VPN solution that is widely used for securing communications over untrusted networks, like the internet.
- IPSec (Internet Protocol Security) is a suite of protocols used to secure internet protocol (IP) communications by authenticating and encrypting each IP packet in a communication session. It ensures the integrity, confidentiality, and authenticity of the data.
Before you begin, it’s important to have a basic understanding of how IPSec VPNs work, including terms like tunnel mode, Phase 1 (IKE – Internet Key Exchange), Phase 2 (IPSec SA – Security Associations), and encryption protocols.
If you are new to Libreswan or IPSec, you might want to review some basic tutorials to familiarize yourself with their concepts. However, even without in-depth knowledge, you can follow this guide step-by-step to set up the VPN.
Ensure Correct Security Group Settings
For the IPSec tunnel to function correctly, you must configure your AWS Security Groups and Network ACLs to allow the required traffic. Here’s what you need to do:
- UDP Ports 500 and 4500 (IKE, NAT-T)
- UDP Port 500 is used by IKE (Internet Key Exchange) for the initial handshake and key exchange between the two VPN endpoints.
- UDP Port 4500 is used for NAT-T (Network Address Translation Traversal). This allows the VPN tunnel to traverse devices like NAT gateways or firewalls that might be altering the IP headers. This port must be open to allow for successful communication when either or both of the EC2 instances are behind a NAT device.
- Protocol 50 (ESP)
- Protocol 50 refers to ESP (Encapsulating Security Payload), which is the IPSec protocol used for encrypting the actual payload of the data being sent across the tunnel. You must allow Protocol 50 in your security settings to ensure that encrypted traffic can flow between the EC2 instances.
Make sure to configure inbound and outbound rules in your Security Groups to allow traffic on these specific ports. This will ensure that IPSec VPN traffic is not blocked.
Access to Modify Route Tables
- Route Tables in AWS define the network traffic flow within and between VPCs. You will need to update the route tables in both VPCs to allow traffic to flow between the two EC2 instances over the VPN tunnel.
- Specifically, you’ll add routes to direct traffic between the subnets in the two VPCs through the VPN endpoints. This ensures that private traffic is routed securely via the IPSec tunnel, rather than through the public internet.
You must have administrative access to modify these route tables in both VPCs to complete the configuration. Be sure to add the necessary routes for the private subnets and the EC2 instances.
Step 2: Install Libreswan on EC2 Instances
In this step, you will install Libreswan, which is the software that will allow your EC2 instances to establish a secure IPSec VPN tunnel. The installation process will vary slightly depending on the Linux distribution running on your EC2 instances. Below are the installation steps for both Amazon Linux 2 and Ubuntu EC2 instances.
Installing Libreswan on Amazon Linux 2
To install Libreswan on an EC2 instance running Amazon Linux 2, follow these steps:
- Connect to your EC2 instance using SSH.
- Example SSH command:
ssh -i /path/to/your-key.pem ec2-user@your-ec2-public-ip
2. Update the package repository to make sure you’re installing the latest version of Libreswan:
sudo yum update -y
3. Install Libreswan using the yum
package manager:
sudo yum install libreswan -y
4. Verify the installation to ensure that Libreswan has been successfully installed:
libreswan --version
This command will display the installed version of Libreswan. If it outputs the version details without any errors, the installation has been completed successfully.
Verifying Installation
Once you’ve completed the installation on both EC2 instances, it’s crucial to verify that Libreswan is installed and running correctly.
- Check the status of the Libreswan service:
- On Amazon Linux 2 and Ubuntu, you can use the following command to check if the Libreswan service is running:
sudo systemctl status ipsec
If Libreswan is installed and running correctly, you should see output indicating that the ipsec
service is active (running).
2. Test the version to make sure you’re working with the correct version of Libreswan:
libreswan --version
- This will return the current version of Libreswan installed on your system.
By successfully installing Libreswan on both EC2 instances, you are now ready to configure the IPSec VPN tunnel. The next step will guide you through configuring the necessary files and settings to establish the VPN connection.
Step 3: Enable IP Forwarding
For your EC2 instances to route packets between networks through the VPN tunnel, IP forwarding must be enabled. This allows the instance to act as a VPN gateway by forwarding traffic between the local VPC and the remote VPC.
Modify sysctl.conf
to Enable IP Forwarding
- Open the
sysctl.conf
file using a text editor:
sudo nano /etc/sysctl.conf
2. Find or add the following line to enable IPv4 forwarding:
net.ipv4.ip_forward = 1
This setting tells the Linux kernel to allow packet forwarding between interfaces.
3. Save the file and exit (Ctrl + X
, then press Y
, and hit Enter
to confirm).
Apply the Changes Immediately
To apply the updated sysctl settings without rebooting the instance, run:
sudo sysctl -p
This command reloads the settings from /etc/sysctl.conf
and activates IP forwarding immediately.
Step 4: Configure Libreswan VPN Tunnel
Now that Libreswan is installed and IP forwarding is enabled, the next step is to configure the IPSec VPN tunnel between your two EC2 instances. This involves setting up the connection parameters in configuration files on both instances.
Step 4.1: Create the Libreswan Configuration File
On both EC2 instances, create a new configuration file at:
sudo nano /etc/ipsec.d/aws.conf
Paste the following template configuration (update the placeholders for your setup):
conn aws-vpn
authby=secret
auto=start
type=tunnel
left=<Public_IP_of_This_Instance>
leftid=<Public_IP_of_This_Instance>
leftsubnet=<CIDR_of_Local_VPC_Subnet>
right=<Public_IP_of_Peer_Instance>
rightid=<Public_IP_of_Peer_Instance>
rightsubnet=<CIDR_of_Remote_VPC_Subnet>
ike=aes256-sha2_256;modp2048
phase2alg=aes256-sha2_256
keyexchange=ikev2
dpdaction=restart
dpddelay=30
dpdtimeout=120
🔸 Replace:
<Public_IP_of_This_Instance>
→ Public Elastic IP of the EC2 you’re editing<Public_IP_of_Peer_Instance>
→ Public Elastic IP of the opposite EC2<CIDR_of_Local_VPC_Subnet>
→ Subnet CIDR block of this instance’s VPC (e.g.,10.0.1.0/24
)<CIDR_of_Remote_VPC_Subnet>
→ Subnet CIDR block of the peer VPC (e.g.,10.0.2.0/24
)
Step 4.2: Add a Pre-Shared Key (PSK)
Now, define the shared secret key that both instances will use to authenticate the VPN connection.
Edit the secrets file:
sudo nano /etc/ipsec.d/aws.secrets
Add the following line (same on both instances):
<Public_IP_of_This_Instance> <Public_IP_of_Peer_Instance> : PSK "YourStrongSecretKey"
🔑 Use a strong, random key for security (you can generate one using openssl rand -base64 32
).
Example:
13.235.10.20 3.91.200.11 : PSK "Z7h@8Gq!9xG2LkP5dTr#UzKz7M"
Step 4.3: Permissions and Validation
Make sure only root can read the secrets file:
sudo chmod 600 /etc/ipsec.d/aws.secrets
Validate your configuration syntax:
sudo ipsec verify
This command checks for configuration errors and confirms required kernel modules are loaded.
✅ Important Notes:
- The
aws.conf
andaws.secrets
files must match exactly on both EC2 instances, except for theleft
/right
values which are mirror images of each other. - Double-check subnet values and ensure they don’t overlap.
- After configuration, restart the IPsec service: bashCopyEdit
sudo systemctl restart ipsec
Step 5: Start and Enable the VPN Service
Once the Libreswan configuration is complete, you need to start the VPN service, enable it on boot, and verify that the tunnel is active.
Step 5.1: Start the Libreswan (IPsec) Service
On both EC2 instances, run the following command to start the IPsec service:
sudo systemctl start ipsec
This will initiate the Libreswan service and attempt to bring up the tunnel using the configuration files you defined earlier.
Step 5.2: Enable the VPN Service at Boot
To ensure the VPN starts automatically whenever the instance reboots, enable the service:
sudo systemctl enable ipsec
This adds Libreswan to the system’s startup services.
Step 5.3: Verify VPN Tunnel Status
To confirm that the VPN tunnel is up and running, use the following command:
sudo ipsec status
You should see output indicating that your aws-vpn
connection is established and security associations (SAs) are active.
For more detailed information:
sudo ipsec statusall
This will show the current state of all tunnels, including which endpoints are connected, negotiated protocols, and any errors if present.
✅ Tip: If the tunnel doesn’t come up, use the following logs to debug:
sudo journalctl -xe
sudo tail -f /var/log/messages # On Amazon Linux
sudo tail -f /var/log/syslog # On Ubuntu
Step 6: Configure Routing and Security Groups
After the VPN tunnel is active, it’s crucial to configure routing and firewall rules to ensure that traffic flows correctly between the two VPCs over the tunnel.
Step 6.1: Update VPC Route Tables
Go to the AWS Console and for each VPC, update the route table associated with your EC2 subnet:
- Add a route in VPC A’s route table:
- Destination: CIDR block of VPC B (e.g.,
10.0.2.0/24
) - Target: Private IP of the EC2 instance in VPC A (the Libreswan VPN gateway)
- Destination: CIDR block of VPC B (e.g.,
- Add a route in VPC B’s route table:
- Destination: CIDR block of VPC A (e.g.,
10.0.1.0/24
) - Target: Private IP of the EC2 instance in VPC B
- Destination: CIDR block of VPC A (e.g.,
🧭 This ensures that traffic to the remote VPC is directed through your VPN gateway EC2 instances.
Step 6.2: Configure Security Groups
Ensure the security groups of both EC2 instances allow the following inbound traffic:
- UDP 500 – for IKE (Internet Key Exchange)
- UDP 4500 – for NAT Traversal
- Protocol 50 (ESP) – IPsec traffic
- ICMP (optional) – For ping testing between VPCs
- VPC Subnet CIDR blocks – Allow traffic from the other VPC’s private subnet
Example rules:
Type | Protocol | Port Range | Source |
---|---|---|---|
Custom UDP | UDP | 500 | VPC B CIDR (e.g., 10.0.2.0/24 ) |
Custom UDP | UDP | 4500 | VPC B CIDR |
Custom Protocol | ESP | All | VPC B CIDR |
ICMP | ICMP | All | VPC B CIDR (optional) |
Apply mirrored rules in the security group of the peer EC2 instance in the other VPC.
Step 6.3: Network ACLs (if applicable)
If your VPC uses custom NACLs, ensure they also allow:
- Inbound and outbound UDP 500, UDP 4500
- ESP (Protocol 50)
- Traffic from both VPC CIDR blocks
✅ Final Check:
- Try pinging a private IP in VPC B from an EC2 instance in VPC A.
- Use
traceroute
ortcpdump
if the traffic doesn’t flow as expected.
Step 7: Test the VPN Tunnel
After setting up routing and security rules, it’s time to validate the VPN tunnel and ensure that both VPCs can securely communicate over their private subnets.
Step 7.1: Ping Across VPCs
From an EC2 instance in VPC A, ping the private IP of an EC2 instance in VPC B:
ping 10.0.2.10 # Replace with the actual private IP of the peer instance
Then, do the reverse from VPC B to VPC A.
✅ If the ping succeeds, your tunnel is passing traffic.
Step 7.2: Use tcpdump
to Verify IPSec Traffic
On each Libreswan EC2 instance, monitor IPSec traffic with tcpdump
:
sudo tcpdump -n -i eth0 esp or udp port 500 or udp port 4500
This command checks for:
- ESP packets (Protocol 50)
- IKE negotiation (UDP 500)
- NAT-T (UDP 4500)
📊 If packets are visible during ping or other traffic, IPSec is working correctly.
Step 7.3: Check VPN Tunnel Health
To confirm the tunnel’s status, run:
sudo ipsec status
Or for more detail:
sudo ipsec statusall
You should see a line like:
"aws-vpn": IPsec SA established
This confirms that the VPN tunnel is active and encrypted traffic is being securely routed.
🔍 Troubleshooting Tips:
- If pings fail, recheck route tables, security groups, and Libreswan configurations.
- Ensure both ends of the tunnel have identical configuration (except
left
andright
IPs/subnets).
9. Best Practices for Managing Libreswan VPN
Maintaining a stable and secure Libreswan VPN setup requires ongoing monitoring and system hardening. Here are some essential best practices to ensure long-term reliability and security of your VPN tunnel:
1. Monitor the VPN Tunnel Health
Set up AWS CloudWatch or use custom shell scripts with cron jobs to monitor the VPN status regularly.
Example script to monitor tunnel status:
#!/bin/bash
if ! ipsec status | grep -q "IPsec SA established"; then
echo "VPN tunnel is down!" | mail -s "Libreswan VPN Alert" [email protected]
fi
You can expand this by integrating with SNS or other alerting tools.
2. Auto-Restart the VPN Service on Failure
Enable automatic recovery in case the VPN service crashes:
sudo systemctl enable ipsec
Additionally, use a systemd service override:
sudo systemctl edit ipsec
Add the following:
[Service]
Restart=on-failure
RestartSec=5s
This ensures that the Libreswan service will restart automatically if it fails.
3. Harden Your EC2 Instances
Secure the instances running the VPN:
- Use SSH key authentication only – Disable password login.
- Disable unused ports – Use security groups and firewalls to restrict access.
- Install Fail2Ban – To protect against SSH brute-force attacks.
- Run as a non-root user wherever possible.
This minimizes exposure and strengthens overall security.
4. Regularly Update Libreswan and the Operating System
Security vulnerabilities are patched frequently. Keep both your Libreswan package and OS up to date:
For Amazon Linux:
sudo yum update libreswan -y
sudo yum update -y
For Ubuntu:
sudo apt update && sudo apt upgrade libreswan -y
Schedule routine updates during maintenance windows to reduce risk.
10. Conclusion
Setting up a Libreswan IPSec VPN tunnel is a powerful and efficient way to achieve secure, inter-regional communication between AWS VPCs. With just a few steps, you can enable private and encrypted connectivity between your EC2 instances—without relying on expensive third-party VPN appliances or AWS Transit Gateway.
This solution is:
- ✅ Cost-effective – You only pay for the EC2 instances and data transfer.
- 🔐 Secure – IPSec ensures that all traffic is encrypted end-to-end.
- 🛠 Flexible – You maintain full control over the configuration and security policies.
Whether you’re running a hybrid architecture, building cross-region failover, or simply need to connect workloads across VPCs, Libreswan provides a reliable foundation for your VPN needs.
Now that you understand how to set it up, go ahead and implement this VPN tunnel to enhance the connectivity and security of your AWS infrastructure.
FAQs – Libreswan IPSec VPN on AWS
Q1: Is Libreswan free to use on AWS EC2?
Yes, Libreswan is an open-source VPN software with no licensing cost. You only pay for the EC2 and network usage.
Q2: Can I use Libreswan for VPC-to-VPC in the same region?
Absolutely! Libreswan works for both inter-regional and intra-regional VPC communication.
Q3: What ports must be open for Libreswan VPN to work?
You need to allow UDP 500, UDP 4500, and Protocol 50 (ESP) in the security groups and NACLs.
Q4: How do I know if my tunnel is active?
Run sudo ipsec status
– if you see “IPsec SA established”, the tunnel is up.
Q5: Does Libreswan support dynamic IPs?
It works best with static (Elastic) IPs. Dynamic IPs may cause instability in tunnel re-negotiation.
Loading newsletter form...