How to Install and Configure OpenVPN on EC2 Amazon Linux 2

Introduction
OpenVPN on EC2
A VPN gives your team encrypted access to private network resources. OpenVPN is a mature, open-source option, and an EC2 instance running Amazon Linux 2 is a cheap place to host it. You get secure access to your network and can resize the instance as your team grows.
Why OpenVPN on Amazon EC2 Linux 2?
Running OpenVPN on EC2 gives you:
- Security: OpenVPN uses strong encryption to tunnel your traffic.
- Scalability and Flexibility: You can move to a larger EC2 instance as your user count grows.
- Cost-Effective: With pay-as-you-go pricing, an EC2 instance can cost less than a traditional VPN appliance or service.
- Customizable: You can tune OpenVPN to match your security and network requirements.
This guide covers prerequisites, installation, configuration, testing, hardening, and maintenance.
Prerequisites
What You Need Before You Start
Have these ready before you install anything:
1. Amazon EC2 Instance Setup
- A running Amazon EC2 instance. If you haven’t launched one before, follow Amazon’s guide on setting up an instance.
- Pick an instance type that fits your expected traffic. Compute-optimized instances are a common choice for VPN servers.
2. Amazon Linux 2 AMI
- Your EC2 instance should run Amazon Linux 2. The commands in this guide use
yumand the Amazon Linux 2 package repositories.
3. Security Group Configuration
- Edit the security group attached to your instance to allow VPN traffic. For OpenVPN that usually means UDP port 1194.
- Limit the rules to the IP ranges your clients connect from.
4. Access Credentials
- Your SSH key pair for the instance. EC2 uses public-key cryptography for login.
- Permission to install software, which means root access or a user with sudo privileges.
5. Network Configuration Knowledge
- You should be comfortable with IP addresses, DNS settings, and routing.
6. Backup Plan
- Take a snapshot or backup of your EC2 instance before you change anything, so you can roll back if something breaks.
Step-by-Step Installation of OpenVPN
Installing the Packages and Building Keys
You’ll install OpenVPN and Easy-RSA, then build the certificates and keys the server and clients need.
Step 1: Connect to Your EC2 Instance
- Connect to your EC2 instance over SSH:
ssh -i /path/to/your-key.pem ec2-user@your-instance-ip
- Replace
/path/to/your-key.pemwith the path to your SSH private key file andyour-instance-ipwith your instance’s public IP address.
Step 2: Update Your System
- Update your system packages:
sudo yum update -y
Step 3: Install OpenVPN and Easy-RSA
- Install OpenVPN and Easy-RSA, a tool for managing OpenVPN keys:
sudo yum install -y openvpn easy-rsa
Step 4: Set Up Easy-RSA
- Copy the Easy-RSA generation scripts to a directory where you’ll manage your keys:
sudo cp -ai /usr/share/easy-rsa/ /etc/openvpn/easy-rsa
- Change to the new directory:
cd /etc/openvpn/easy-rsa/3/
- Initialize the PKI (Public Key Infrastructure):
./easyrsa init-pki
Step 5: Build the CA (Certificate Authority)
- Build your CA. It signs the server and client certificates:
./easyrsa build-ca nopass
- Easy-RSA prompts you for a name for your CA.
Step 6: Create Server Certificate and Key
- Generate a server certificate and key:
./easyrsa build-server-full server nopass
Step 7: Generate Client Certificate and Key
- Generate a certificate and key for each client:
./easyrsa build-client-full client1 nopass
- Replace
client1with your desired client name.
Step 8: Generate the DH Parameters
- Generate the Diffie-Hellman parameters for key exchange:
./easyrsa gen-dh
Step 9: Configure OpenVPN
- Copy the necessary files to the OpenVPN directory:
sudo cp /etc/openvpn/easy-rsa/3/pki/ca.crt /etc/openvpn/
sudo cp /etc/openvpn/easy-rsa/3/pki/issued/server.crt /etc/openvpn/
sudo cp /etc/openvpn/easy-rsa/3/pki/private/server.key /etc/openvpn/
sudo cp /etc/openvpn/easy-rsa/3/pki/dh.pem /etc/openvpn/
- Next, edit the server configuration file, covered below.
Configuring OpenVPN
Editing server.conf
Now set up the server configuration for your network.
Step 1: Access the OpenVPN Server Configuration File
- The server configuration file lives at
/etc/openvpn/server.conf. Open it in an editor such asnano:
sudo nano /etc/openvpn/server.conf
Step 2: Configure Basic Server Settings
- Set the port, protocol, and device type:
port 1194
proto udp
dev tun
port 1194specifies the port OpenVPN will listen on.proto udpsets the protocol to UDP, the usual choice for VPNs.dev tunspecifies the use of a tunneled virtual ethernet device.
Step 3: Specify Paths to Certificates and Keys
- Point the server at the CA, certificate, and key files:
ca ca.crt
cert server.crt
key server.key
dh dh.pem
- These paths must match where you copied the certificates and keys during installation.
Step 4: Configure VPN Network Settings
- Set the IP range OpenVPN assigns to clients:
server 10.8.0.0 255.255.255.0
- This example sets the VPN subnet to
10.8.0.0.
Step 5: Route All Client Traffic Through the VPN
- To send all client traffic through the VPN server (full tunnel), add:
push "redirect-gateway def1 bypass-dhcp"
- This directive tells clients to use the VPN as their default gateway. For it to reach the internet, the server must also forward and NAT that traffic, which you set up in Step 9.
- Leave this line out if clients only need to reach resources inside your VPC (split tunnel).
Step 6: DNS Configuration
- Push DNS servers to clients so they can resolve domain names:
push "dhcp-option DNS 8.8.8.8"
push "dhcp-option DNS 8.8.4.4"
- These lines use Google’s DNS servers as an example.
Step 7: Additional Security and Performance Settings
- Enable client-to-client traffic if you need it, and add keepalive and persistence settings:
client-to-client
keepalive 10 120
comp-lzo
persist-key
persist-tun
Step 8: Save and Exit
- Save the file and exit.
Step 9: Enable IP Forwarding and NAT
- By default, Linux does not forward packets between interfaces. Turn on IP forwarding and make it persist across reboots:
echo 'net.ipv4.ip_forward = 1' | sudo tee /etc/sysctl.d/99-openvpn.conf
sudo sysctl --system
- Check that it took effect. The command should print
net.ipv4.ip_forward = 1:
sysctl net.ipv4.ip_forward
- Find the instance’s primary network interface. On Amazon Linux 2 it is usually
eth0. The interface name followsdevin the output:
ip route show default
- Add a NAT (masquerade) rule so traffic from the VPN subnet leaves through that interface with the instance’s address. Replace
eth0if your interface has a different name:
sudo iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
- Rules added with
iptablesare lost on reboot. Installiptables-servicesto save them and load them at boot:
sudo yum install -y iptables-services
sudo service iptables save
sudo systemctl enable iptables
service iptables savewrites the current rules to/etc/sysconfig/iptables, which theiptablesservice loads at boot. Run the save after you add the NAT rule. It replaces the package’s default rules file, which rejects forwarded traffic and most inbound ports.- If the instance already has its own
iptablesrules in thefiltertable that drop forwarded traffic, allow traffic from thetun0interface in theFORWARDchain as well. - Confirm the security group allows inbound UDP port 1194, the port set in Step 2.
Step 10: Start the OpenVPN Service
- Start the OpenVPN service and enable it at boot:
sudo systemctl start openvpn@server
sudo systemctl enable openvpn@server
The server should now be running. Test it before you hand out client configs.

Testing the OpenVPN Connection
Checking Connectivity and Leaks
Connect from a client device and confirm that traffic flows and nothing leaks outside the tunnel.
Step 1: Download the Client Configuration File
- You need a client configuration file, usually named
client.ovpn. It contains the client’s certificate and key, the CA certificate, and the OpenVPN client settings. - Copy this file to your client device over a secure channel.
Step 2: Install an OpenVPN Client
- Install an OpenVPN client on your device. Clients exist for Windows, macOS, Linux, and mobile platforms.
Step 3: Connect to the VPN Server
- Import
client.ovpninto the client and connect to your VPN server. - If you added extra authentication methods, enter those credentials.
Step 4: Verify the Connection
- Check that the client’s assigned IP address falls within the range you set in the server configuration.
- Use
pingortracerouteto confirm you can reach your EC2 instance and other resources on your network.
Step 5: Test Internet Connectivity
- If you route internet traffic through the VPN, visit a site like
ipleak.netand confirm your public IP address matches the VPN server’s IP.
Step 6: Check for DNS Leaks
- Your DNS queries should go through the VPN too. Run an online DNS leak test to check.
Step 7: Troubleshooting
- If something fails, compare your server and client configuration files for mismatches.
- Read the logs on the server (
/var/log/openvpn.log) and on the client for error messages.
When the connection works and the leak tests pass, your server is ready for users.

Securing Your OpenVPN Installation
Hardening the Server
Your VPN server is an entry point into your network, so lock it down:
1. Update Regularly
- Apply security patches to Amazon Linux 2 and the OpenVPN package on a schedule:
sudo yum update -y
2. Implement Strong Authentication Mechanisms
- Add a second factor on top of certificates, such as two-factor authentication (2FA).
3. Harden the Server Configuration
- Review
server.confand disable features you don’t use. - Use strong TLS settings and disable weak ciphers with the
tls-cipherandcipherdirectives.
4. Secure Communication Channels
- Encrypt all communication with the server, including the transfer of configuration files and keys to clients.
5. Firewall Configuration
- Configure the instance firewall to allow only the traffic the VPN needs, so less of the server faces the internet.
- Use security groups to control inbound and outbound traffic to the instance.
6. Manage User Access and Keys
- Audit user access. Revoke certificates for users who no longer need the VPN, and rotate keys.
- Give each user a unique certificate and key so you can trace and revoke access per person.
7. Monitor and Log Activity
- Turn on logging and monitoring, and review the logs for unusual activity.
- Use CloudWatch to monitor performance and set up alerts.
8. Regular Security Audits
- Audit your VPN setup periodically and fix the vulnerabilities you find.
- Follow security advisories for OpenVPN and VPN infrastructure.

Maintaining and Updating OpenVPN
A Maintenance Routine
Set up a routine so the server stays patched and reliable:
1. Schedule Regular Updates
- Update OpenVPN and Amazon Linux 2 to pick up security patches and performance fixes.
- Automate updates with a cron job or AWS management tools.
2. Monitor VPN Performance and Usage
- Watch your VPN’s performance metrics for traffic spikes or speed drops.
- Use Amazon CloudWatch for real-time monitoring and alerts.
3. Backup VPN Configuration and Data
- Back up your OpenVPN configuration files and PKI so you can recover after a failure or breach.
- Store backups in Amazon S3 or take EBS snapshots.
4. Review Security Group and Firewall Settings
- Review the instance’s security group and firewall settings and update them to match your current security policies.
5. Audit User Access and Authentication Methods
- Review who has VPN access and remove users who no longer need it.
- Keep any extra authentication methods up to date.
6. Keep Abreast of Latest Security Practices
- Follow security forums and the update announcements from OpenVPN and AWS.
7. Conduct Regular Security Audits
- Audit your VPN setup for vulnerabilities, with internal reviews and external penetration tests.
8. Document Changes and Procedures
- Document every change, update, and procedure for your OpenVPN setup. Whoever maintains or troubleshoots the server next will need it.


