Building a VPN on Cloud Servers: Practical Configuration of Security Groups, Firewalls, and Key Management
1. Security Group Configuration: The First Line of Defense
When building a VPN on a cloud server, security groups are the core of network access control. First, log in to your cloud provider's console and locate the security group associated with your instance. When adding inbound rules, only open necessary ports:
- SSH port (22): Restrict source IP to the administrator's IP to prevent brute force attacks.
- VPN protocol ports:
- OpenVPN: UDP 1194 (default)
- WireGuard: UDP 51820 (default)
- IPsec IKEv2: UDP 500, 4500
- ICMP protocol: Optionally enable for network connectivity testing.
Outbound rules typically allow all traffic by default, but you can further restrict to only allow VPN tunnel traffic.
2. Firewall Rules: Fine-Grained Control at the OS Level
The internal firewall on the cloud server (e.g., iptables/nftables) provides a second layer of protection. Using Ubuntu 22.04 as an example:
- Enable UFW:
sudo ufw enable - Set default policies:
sudo ufw default deny incoming,sudo ufw default allow outgoing - Open VPN ports:
sudo ufw allow 1194/udp - Allow SSH:
sudo ufw allow from <admin IP> to any port 22 - Enable IP forwarding: Edit
/etc/sysctl.conf, uncommentnet.ipv4.ip_forward=1, runsysctl -p.
For WireGuard, you also need to configure PostUp/PostDown scripts to add NAT rules:
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
3. Key Management: Ensuring Communication Security
VPNs rely on encryption keys to secure data transmission.
3.1 Generating Strong Keys
- OpenVPN: Use
easy-rsato generate CA certificates, server certificates, and client certificates. A key length of at least 2048 bits is recommended. - WireGuard:
wg genkey | tee privatekey | wg pubkey > publickey, set private key permissions to 600.
3.2 Key Storage and Rotation
- Store private keys in
/etc/wireguard/or/etc/openvpn/with permissions 600. - Rotate keys periodically: WireGuard supports dynamic updates via
wg setwithout restarting the service. - Use Hardware Security Modules (HSM) or Key Management Services (KMS) to protect critical keys.
3.3 Client Certificate Revocation
- OpenVPN: Use
easy-revoketo revoke certificates and update the CRL. - WireGuard: Delete the public key from the client configuration or restart the server.
4. Practical Verification and Monitoring
After configuration, perform the following verifications:
- Connect to the VPN from a client and check if the IP address changes to the server's IP.
- Use
tcpdumpto capture packets and confirm traffic encryption. - Configure log monitoring:
journalctl -u wg-quick@wg0to view WireGuard logs.
Regularly review security group and firewall rules, removing unused ports.