首先,确保已更新系统并安装了OpenVPN及相关工具:
apt update apt install openvpn easy-rsa
接着,需要修改防火墙规则以允许1194/TCP/UDP端口的流量:
# 添加防火墙规则以允许1194/TCP/UDP
apt update apt list openvpn apt install openvpn easy-rsa openvpn -V
cd /opt/ && mkdir easy-rsa && cd easy-rsa cd /usr/share/easy-rsa/ && mv ./* /opt/easy-rsa/ cd /opt/easy-rsa/ cp vars.example vars
编辑
vars
文件,修改证书有效期:
vim vars # CA的证书默认有效期为10年,可以适当延长,比如:36500天 set_var EASYRSA_CA_EXPIRE 36500 # 服务器证书默认为825天,可适当加长,比如:3650天 set_var EASYRSA_CERT_EXPIRE 3650
初始化PKI并生成相关目录和文件:
./easyrsa init-pki
创建CA机构证书环境:
./easyrsa build-ca nopass
创建服务器证书申请文件:
./easyrsa gen-req server nopass
颁发服务端证书:
./easyrsa sign server server
创建密钥:
./easyrsa gen-dh
创建客户端证书申请:
./easyrsa gen-req xiaowang nopass ./easyrsa sign client xiaowang
将CA和服务器证书相关文件复制到服务器相应的目录:
cp pki/ca.crt /etc/openvpn/server/ cp pki/issued/server.crt /etc/openvpn/server/ cp pki/private/server.key /etc/openvpn/server/ cp pki/dh.pem /etc/openvpn/server/
将客户端私钥与证书相关文件复制到服务器相关的目录:
mkdir /etc/openvpn/client/xiaowang cp /opt/easy-rsa/pki/ca.crt /etc/openvpn/client/xiaowang/ cp /opt/easy-rsa/pki/private/xiaowang.key /etc/openvpn/client/xiaowang/ cp /opt/easy-rsa/pki/issued/xiaowang.crt /etc/openvpn/client/xiaowang/
拷贝示例配置文件并查看配置选项:
cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf /etc/openvpn/ cd /etc/openvpn/
查看配置文件并根据需要进行修改:
grep -Ev "^#|^$" /etc/openvpn/server.conf
修改服务器端配置文件:
vim /etc/openvpn/server.conf
port 1194 proto udp dev tun ca /etc/openvpn/server/ca.crt cert /etc/openvpn/server/server.crt key /etc/openvpn/server/server.key # This file should be kept secret dh /etc/openvpn/server/dh.pem topology subnet server 10.8.0.0 255.255.255.0 ifconfig-pool-persist /var/log/openvpn/ipp.txt keepalive 10 120 cipher AES-256-CBC max-clients 50 user root group root persist-key persist-tun status /var/log/openvpn/openvpn-status.log log-append /var/log/openvpn/openvpn.log verb 6 mute 20 explicit-exit-notify 1
adduser --system --home /etc/openvpn --ingroup openvpn --shell /usr/sbin/nologin openvpn chown -R openvpn:openvpn /etc/openvpn mkdir /var/log/openvpn chown openvpn.openvpn /var/log/openvpn
systemctl start openvpn@server
systemctl status openvpn@server
ip a
46: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 500 link/none inet 10.8.0.1/24 scope global tun0 valid_lft forever preferred_lft forever inet6 fe80::463f:5825:8bf4:5e2/64 scope link stable-privacy valid_lft forever preferred_lft forever
grep '^[[:alpha:]].*' /usr/share/doc/openvpn/examples/sample-config-files/client.conf > /etc/openvpn/client/xiaowang/client.ovpn
编辑客户端配置文件:
vim /etc/openvpn/client/xiaowang/client.ovpn
client dev tun proto udp remote 服务器ip 1194 resolv-retry infinite nobind #persist-key #persist-tun ca ca.crt cert wangqing.crt key wangqing.key remote-cert-tls server #tls-auth ta.key 1 cipher AES-256-CBC verb 3
请根据需要调整配置,然后可以使用生成的客户端配置连接到服务器。