在Linux上建立VPN有多种方式,以下是几种常见的方法,包括 IPSec (StrongSwan/Libreswan)、OpenVPN、WireGuard 和 SoftEther VPN,下面以 WireGuard(轻量级、高性能)和 OpenVPN(传统稳定)为例:
方法1:使用 WireGuard(推荐)
WireGuard 是现代、快速且配置简单的VPN协议。
安装 WireGuard
# CentOS/RHEL sudo yum install epel-release sudo yum install wireguard-tools
生成密钥对
cd /etc/wireguard umask 077 wg genkey | tee privatekey | wg pubkey > publickey
配置服务端 (/etc/wireguard/wg0.conf)
[Interface] Address = 10.0.0.1/24 ListenPort = 51820 PrivateKey = <服务器私钥(privatekey文件内容)> # 允许客户端流量转发(需启用IP转发) PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE # 客户端配置(示例) [Peer] PublicKey = <客户端公钥> AllowedIPs = 10.0.0.2/32
启用IP转发
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf sudo sysctl -p
启动 WireGuard
sudo systemctl enable wg-quick@wg0 sudo systemctl start wg-quick@wg0
客户端配置
客户端需安装WireGuard并创建类似的配置文件(交换公钥和IP)。
方法2:使用 OpenVPN
安装 OpenVPN 和 EasyRSA
# CentOS/RHEL sudo yum install openvpn easy-rsa
生成CA和证书
mkdir -p ~/easy-rsa/keys cp -r /usr/share/easy-rsa/3/* ~/easy-rsa/ cd ~/easy-rsa ./easyrsa init-pki ./easyrsa build-ca # 输入CA密码和名称 ./easyrsa gen-req server nopass # 服务器证书 ./easyrsa sign-req server server # 签名 ./easyrsa gen-dh # Diffie-Hellman参数
配置服务端 (/etc/openvpn/server.conf)
port 1194 proto udp dev tun ca /path/to/ca.crt cert /path/to/server.crt key /path/to/server.key dh /path/to/dh.pem 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 comp-lzo persist-key persist-tun status openvpn-status.log verb 3
启动 OpenVPN
sudo systemctl enable openvpn@server sudo systemctl start openvpn@server
生成客户端证书
./easyrsa gen-req client1 nopass ./easyrsa sign-req client client1
客户端需使用 .ovpn 配置文件(包含证书和密钥)。
防火墙设置
确保放行VPN端口:
- WireGuard: UDP 51820
- OpenVPN: UDP 1194
sudo ufw allow 51820/udp # WireGuard sudo ufw allow 1194/udp # OpenVPN
注意事项
- 安全性:确保使用强加密算法,定期更新密钥。
- 日志监控:检查
/var/log/syslog或journalctl -u openvpn排查问题。 - 多客户端:在WireGuard或OpenVPN中添加多个
[Peer]或客户端证书。
如果需要更简单的方案,可考虑 SoftEther VPN(支持多协议)或商业解决方案如 Tailscale(基于WireGuard的零配置VPN)。



