How to Set Up Your Own VPN Server on AWS EC2
Setting up a VPN server on an AWS EC2 instance allows you to secure your internet traffic. Here’s a complete step-by-step guide for setting up a VPN using OpenVPN on an Amazon EC2 instance.
Step 1: Create an AWS EC2 Instance
- Log into the AWS Management Console.
- Navigate to EC2: Go to the EC2 Dashboard and click Launch Instance.
- Choose an Amazon Machine Image (AMI): Select the Ubuntu Server (22.04 or similar Linux distribution).
- Choose Instance Type: Use t2.micro or t3.micro for personal use.
- Configure Instance Details:
- Ensure that the instance is in the Default VPC.
- Enable Auto-assign Public IP.
- Configure Security Group:
- Create a new security group or use an existing one.
- Open these ports:
- UDP 1194 (for OpenVPN)
- TCP 22 (for SSH access)
- Launch the Instance and connect to it once running.
Step 2: Connect to Your EC2 Instance via SSH
- Connect via SSH:
ssh -i your_key.pem ubuntu@your_ec2_public_ip
Step 3: Install OpenVPN and Easy-RSA
- Update the Server:
sudo apt update && sudo apt upgrade -y
- Install OpenVPN:
sudo apt install openvpn -y
- Install Easy-RSA:
sudo apt install easy-rsa -y
Step 4: Configure Easy-RSA and Generate Certificates
- Set Up PKI Directory:
make-cadir ~/openvpn-ca cd ~/openvpn-ca
- Edit the vars File:
nano vars
Update values like
KEY_COUNTRY
,KEY_PROVINCE
, etc. - Generate Certificates:
source vars ./clean-all ./build-ca
- Create a Server Certificate and Key:
./build-key-server server
- Generate Diffie-Hellman Key:
./build-dh
- Generate TLS Key:
openvpn --genkey --secret keys/ta.key
Step 5: Configure the OpenVPN Server
- Copy Server Certificate Files:
sudo cp ~/openvpn-ca/keys/ {server.crt,server.key,ca.crt,dh2048.pem,ta.key} /etc/openvpn
- Create OpenVPN Server Config:
sudo nano /etc/openvpn/server.conf
Add the following configuration:
port 1194 proto udp dev tun ca ca.crt cert server.crt key server.key dh dh2048.pem tls-auth ta.key 0 server 10.8.0.0 255.255.255.0 push "redirect-gateway def1 bypass-dhcp" push "dhcp-option DNS 8.8.8.8" keepalive 10 120 cipher AES-256-CBC user nobody group nogroup persist-key persist-tun verb 3
- Enable IP Forwarding:
sudo nano /etc/sysctl.conf
Uncomment or add
net.ipv4.ip_forward=1
, then apply:sudo sysctl -p
- Configure UFW Firewall:
sudo ufw allow 1194/udp sudo ufw allow OpenSSH
Step 6: Start and Enable OpenVPN
sudo systemctl start openvpn@server
sudo systemctl enable openvpn@server
Step 7: Configure Client Files
- Generate Client Certificate:
cd ~/openvpn-ca source vars ./build-key clientname
- Create Client Config:
nano ~/client.ovpn
Add the configuration:
client dev tun proto udp remote your_ec2_public_ip 1194 resolv-retry infinite nobind remote-cert-tls server auth SHA256 cipher AES-256-CBC key-direction 1
Step 8: Connect to VPN
Transfer the .ovpn
file to your device and use OpenVPN client to connect.