目 录CONTENT

文章目录

阿里云ECS上搭建OpenVPN服务器

简中仙
2023-11-15 / 0 评论 / 0 点赞 / 3065 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于2024-03-27,若内容或图片失效,请留言反馈。 本文如有错误或者侵权的地方,欢迎您批评指正!

一、应用环境

办公地点:公司办公楼,无外网IP地址,工作时间无限制,配置有联通300M宽带

服务器:阿里云ECS服务器一台

之前办公:

由于工作需要,公司内部要部署一个wiki系统,由于wiki软件漏洞层出不穷且没有实体服务器,被迫向公网开放,频繁遭受到黑客的攻击。

改造后要实现的目标:

wiki系统要仅能通过内网访问,同时要保证wiki系统的安全。

方案:

阿里云ECS上安装OpenVPN服务器,将wiki服务器放置到服务器上,服务器和所有员工使用的电脑通过VPN证书连接虚拟网络,这样就可以通过VPN穿透联通宽带的内网线路限制。

二、安装部署

  • 系统平台:Centos7.9
  • OpenVPN版本:2.4.12
  • easy-rsa 版本:3.0.8

1、配置软件源(安装epel)

yum -y install epel-release
yum update

2、安装软件

yum -y install openvpn easy-rsa iptables-services openvpn-auth-ldap

3、生成证书

1、创建证书环境目录

mkdir -p /etc/openvpn/easy-rsa/
# 这下边哪个目录都行,其实都是软链的关系
cp -a /usr/share/easy-rsa/3/* /etc/openvpn/easy-rsa/
# 这下边哪个目录都行,其实都是软链的关系
cp -a /usr/share/doc/easy-rsa-3.0.8/vars.example /etc/openvpn/easy-rsa/vars

2、配置环境变量

修改文件/etc/openvpn/easy-rsa/vars中的如下配置(要取消注释)

if [ -z "$EASYRSA_CALLER" ]; then
        echo "You appear to be sourcing an Easy-RSA 
'vars' file." >&2
        echo "This is no longer necessary and is 
disallowed. See the section called" >&2
        echo "'How to use this file' near the top 
comments for more details." >&2
       return 1
fi
set_var EASYRSA_DN "cn_only"
set_var EASYRSA_REQ_COUNTRY "CN"							# 所在的国家
set_var EASYRSA_REQ_PROVINCE "Shanxi"						# 所在的省份
set_var EASYRSA_REQ_CITY "Taiyuan"							# 所在的城市
set_var EASYRSA_REQ_ORG "xxxxx"								# 所在的组织
set_var EASYRSA_REQ_EMAIL "1234567981011@163.com"			# 邮箱的地址
set_var EASYRSA_NS_SUPPORT "yes"

3、生成 CA 根证书

在当前目录下创建pki目录,用于存储证书

# cd /etc/openvpn/easy-rsa
# ./easyrsa init-pki

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /etc/openvpn/easy-rsa/pki

根证书用于ca对之后生成的server和client证书签名时使用。(输入两次密码,直接回车)

# ./easyrsa build-ca

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017

Enter New CA Key Passphrase: 							# 密码
Re-Enter New CA Key Passphrase: 						# 重复密码
Generating RSA private key, 2048 bit long modulus
...................................+++
...........................................+++
e is 65537 (0x10001)
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:

CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/etc/openvpn/easy-rsa/pki/ca.crt

4、创建server端证书和私钥文件

nopass表示不加密私钥文件,生成过程中直接回车默认

# ./easyrsa gen-req server nopass

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017
Generating a 2048 bit RSA private key
...+++
.+++
writing new private key to '/etc/openvpn/easy-rsa/pki/easy-rsa-2658.ST8bIw/tmp.7PKcpO'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [server]:

Keypair and certificate request completed. Your files are:
req: /etc/openvpn/easy-rsa/pki/reqs/server.req
key: /etc/openvpn/easy-rsa/pki/private/server.key

给server端证书签名,提示内容需要输入yes和创建ca根证书时候的密码

# ./easyrsa sign server server

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017


You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.

Request subject, to be signed as a server certificate for 825 days:

subject=
    commonName                = server


Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: yes							# 输入yes
Using configuration from /etc/openvpn/easy-rsa/pki/easy-rsa-3961.Ciu72E/tmp.RrrscH
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:			# 输入密码
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'server'
Certificate is to be certified until Feb 16 03:30:52 2026 GMT (825 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /etc/openvpn/easy-rsa/pki/issued/server.crt

5、创建Diffie-Hellman文件

秘钥交换时的Diffie-Hellman算法

# ./easyrsa gen-dh

6、生成 tls-auth key

这个 key 主要用于防止 DoS 和 TLS 攻击,这一步其实是可选的,但为了安全还是生成一下,该文件在后面配置 open VPN 时会用到。

# openvpn --genkey --secret ta.key

7、创建client端证书和私钥文件

nopass表示不加密私钥文件,生成过程中直接回车默认

# ./easyrsa gen-req client nopass

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017
Generating a 2048 bit RSA private key
....................................................+++
....................+++
writing new private key to '/etc/openvpn/easy-rsa/pki/easy-rsa-6032.0xEnLe/tmp.tjXAe5'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [client]:

Keypair and certificate request completed. Your files are:
req: /etc/openvpn/easy-rsa/pki/reqs/client.req
key: /etc/openvpn/easy-rsa/pki/private/client.key

给client端证书签名,提示内容输入yes和创建ca根证书时候的密码

# ./easyrsa sign client client

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017


You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.

Request subject, to be signed as a client certificate for 825 days:

subject=
    commonName                = client


Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: yes				# 输入yes
Using configuration from /etc/openvpn/easy-rsa/pki/easy-rsa-6482.mHIDrY/tmp.yZDeMV
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:			# 输入密码
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'client'
Certificate is to be certified until Feb 16 03:32:32 2026 GMT (825 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /etc/openvpn/easy-rsa/pki/issued/client.crt

4、优化证书目录

# mkdir /etc/openvpn/server/certs && cd /etc/openvpn/server/certs
# cp /etc/openvpn/easy-rsa/pki/dh.pem ./
# cp /etc/openvpn/easy-rsa/pki/ca.crt ./
# cp /etc/openvpn/easy-rsa/pki/issued/server.crt ./
# cp /etc/openvpn/easy-rsa/pki/private/server.key ./
# cp /etc/openvpn/easy-rsa/ta.key ./

5、创建 open VPN 日志目录

mkdir -p /var/log/openvpn/
chown openvpn:openvpn /var/log/openvpn

三、OpenVPN服务端部署

1、修改配置文件

注意,openvpn会使用udp 1194端口,云服务器需要在云控制台的安全组中将其开放

自行创建配置文件/etc/openvpn/server.conf,并加入如下配置

# 监听的端口号
port 1194
# 服务端用的协议,udp 能快点,所以我选择 udp
proto udp
# 定义openvpn运行时使用哪一种模式,openvpn有两种运行模式一种是tap模式,一种是tun模式。
# tap模式也就是桥接模式,通过软件在系统中模拟出一个tap设备,该设备是一个二层设备,同时支持链路层协议。
# tun模式也就是路由模式,通过软件在系统中模拟出一个tun路由,tun是ip层的点对点协议。
dev tun
# 定义openvpn在使用tun路由模式时,分配给client端分配的IP地址段
server 10.106.0.0 255.255.255.0
# 这条命令可以重定向客户端的网关,在进行翻墙时会使用到
push "redirect-gateway def1 bypass-dhcp"
# 向客户端推送的路由信息,如下内容表示客户端连接之后与当前互通
push "route 192.168.0.0 255.255.255.0" 
push "route 10.0.0.0 255.255.0.0"
# 向客户端推送的DNS信息
push "dhcp-option DNS 223.5.5.5"
push "dhcp-option DNS 223.6.6.6"
push "dhcp-option DNS 114.114.114.114"
# 定义活动连接保时期限
keepalive 10 300
# 加密类型
cipher AES-256-CBC
# 启用允许数据压缩,客户端配置文件也需要有这项
comp-lzo
# 最多允许连接1000个客户端
max-clients 1000
# 通过keepalive检测超时后,重新启动VPN,不重新读取keys,保留第一次使用的keys
persist-key
# 通过keepalive检测超时后,重新启动VPN,一直保持tun或者tap设备是linkup的。否则网络连接,会先linkdown然后再linkup
persist-tun
# 指定日志文件的记录详细级别,可选0-9,等级越高日志内容越详细
verb 4
# 重复日志记录限额
mute 20
# 禁用TSL重协商
reneg-sec 0
# 此选项开启只能使用udp协议。否则会报错error: --explicit-exit-notify can only be used with --proto udp
explicit-exit-notify 1
# 客户端1,服务端是0
key-direction 0
# 2.4版本之前使用 tls-auth,如果高于此版本,则用tls-crypt,我用的2.4.8使用了tls-auth,结果连通之后无法访问外网了
# tls-auth key,参数 0 可以省略,如果不省略,那么客户端配置相应的参数该配成 1。如果省略,那么客户端不需要 tls-auth 配置
tls-crypt /etc/openvpn/server/certs/ta.key 0
# 记录客户端和虚拟ip地址之间的关系。在openvpn重启时,再次连接的客户端将依然被分配和断开之前的IP地址
ifconfig-pool-persist /etc/openvpn/ipp.txt
# 使用客户提供的UserName作为Common Name
username-as-common-name
# 基于mysql进行认证,如不需要可注释掉,注意最后的openvpn_mysql是与后边配置文件名称相呼应的
# plugin      /etc/openvpn/openvpn-plugin-auth-pam.so openvpn_mysql
# 基于ldap进行认证,如不需要可注释掉,注意最后的/etc/openvpn/auth/ldap.conf是与后边配置文件名称相呼应的
# plugin /usr/lib64/openvpn/plugin/lib/openvpn-auth-ldap.so "/etc/openvpn/auth/ldap.conf"
# CA 根证书路径
ca /etc/openvpn/server/certs/ca.crt
# open VPN 服务器证书路径
cert /etc/openvpn/server/certs/server.crt
# open VPN 服务器密钥路径
key /etc/openvpn/server/certs/server.key
# Diffie-Hellman 算法密钥文件路径
dh /etc/openvpn/server/certs/dh.pem
# 指定 log 文件位置
log /var/log/openvpn/server.log
log-append /var/log/openvpn/server.log
status /var/log/openvpn/status.log

2、设置 iptables

1、关闭防火墙和SELinux

systemctl stop firewalld
systemctl mask firewalld
setenforce 0				# 临时关闭
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config			# 永久关闭,重启服务器后生效

2、启用iptables

systemctl enable iptables
systemctl start iptables
iptables -F   # 清理所有防火墙规则

3、添加防火墙规则

将 openvpn 的网络流量转发到公网:snat 规则

# 如下网段记得与server.conf 当中定义的网段保持一致
iptables -t nat -A POSTROUTING -s 10.106.0.0/24 -o eth0 -j MASQUERADE
iptables -L -t nat
iptables-save > /etc/sysconfig/iptables   # iptables 规则持久化保存

4、启用地址转发

设置前请确保 iptables 已经开启,而且 /etc/sysconfig/iptables 文件已存在。然后开启转发:

echo net.ipv4.ip_forward = 1 >> /etc/sysctl.conf
sysctl -p # 这一步一定得执行,否则不会立即生效。

3、启动openvpn

systemctl -f enable openvpn@server.service	  	# 开机自启
systemctl start openvpn@server.service			# 启动服务
systemctl status openvpn@server  				# 查看服务状态

四、登录认证

1、使用默认方式做登录认证

1、创建用户

首先创建一个客户端配置模板文件 sample.ovpn,该文件在脚本中会用到,放到 /etc/openvpn/client/ 目录。cat /etc/openvpn/client/sample.ovpn:

# 指定这是一个客户端,我们将从服务器获取某些配置文件指令
client
# 在大多数系统中,除非你部分禁用或者完全禁用了TUN/TAP接口的防火墙,否则VPN将不起作用
dev tun
# 指定连接的服务器是采用TCP还是UDP协议,这里需要使用与服务器端相同的设置
proto udp
# 指定服务器的主机名(或IP)以及端口号,如果有多个VPN服务器,为了实现负载均衡,你可以设置多个remote指令
remote my-server-1 1198
;remote my-server-2 1198
# 启用该指令,与服务器连接中断后将自动重新连接,这在网络不稳定的情况下(例如:笔记本电脑无线网络)非常有用
resolv-retry infinite
# 大多数客户端不需要绑定本机特定的端口号
nobind
# 持久化选项可以尽量避免访问在重启时由于用户权限降低而无法访问的某些资源
persist-key
persist-tun
remote-cert-tls server
# 启用允许数据压缩,服务端配置文件也需要有这项
comp-lzo
# 指定日志文件的记录详细级别,可选0-9,等级越高日志内容越详细
verb 3
auth-nocache
script-security 3
ca ca.crt
cert admin.crt
key admin.key
tls-crypt ta.key 1

**注意:**要把配置文件中的my-server-1替换为你openvpn服务器的真实地址

下面为创建 open VPN 用户脚本cat /etc/openvpn/client/ovpn_user.sh:

# ! /bin/bash
set -e
OVPN_USER_KEYS_DIR=/etc/openvpn/client/keys
EASY_RSA_DIR=/etc/openvpn/easy-rsa/
PKI_DIR=$EASY_RSA_DIR/pki
for user in "$@"
do
  if [ -d "$OVPN_USER_KEYS_DIR/$user" ]; then
    rm -rf $OVPN_USER_KEYS_DIR/$user
    rm -rf  $PKI_DIR/reqs/$user.req
    sed -i '/'"$user"'/d' $PKI_DIR/index.txt
  fi
  cd $EASY_RSA_DIR
  # 生成客户端 ssl 证书文件
  ./easyrsa build-client-full $user nopass
  # 整理下生成的文件
  mkdir -p  $OVPN_USER_KEYS_DIR/$user
  cp $PKI_DIR/ca.crt $OVPN_USER_KEYS_DIR/$user/   # CA 根证书
  cp $PKI_DIR/issued/$user.crt $OVPN_USER_KEYS_DIR/$user/   # 客户端证书
  cp $PKI_DIR/private/$user.key $OVPN_USER_KEYS_DIR/$user/  # 客户端证书密钥
  cp /etc/openvpn/client/sample.ovpn $OVPN_USER_KEYS_DIR/$user/$user.ovpn # 客户端配置文件
  sed -i 's/admin/'"$user"'/g' $OVPN_USER_KEYS_DIR/$user/$user.ovpn
  cp /etc/openvpn/server/certs/ta.key $OVPN_USER_KEYS_DIR/$user/ta.key  # auth-tls 文件
  cd $OVPN_USER_KEYS_DIR
  zip -r $user.zip $user
done
exit 0

执行上面脚本创建一个用户:sh ovpn_user.sh testuser1

$ sh ovpn_user.sh testuser1
Note: using Easy-RSA configuration from: ./vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017
Generating a 2048 bit RSA private key
.......+++
....................................+++
writing new private key to '/etc/openvpn/easy-rsa/pki/private/testuser1.key.wwfcLvbunb'
-----
Using configuration from /etc/openvpn/easy-rsa/pki/safessl-easyrsa.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'testuser1'
Certificate is to be certified until Jan 16 09:36:22 2023 GMT (1080 days)
Write out database with 1 new entries
Data Base Updated
  adding: testuser1/ (stored 0%)
  adding: testuser1/testuser1.ovpn (deflated 30%)
  adding: testuser1/ca.crt (deflated 26%)
  adding: testuser1/testuser1.key (deflated 23%)
  adding: testuser1/testuser1.crt (deflated 46%)
  adding: testuser1/ta.key (deflated 40%)

会在 /etc/openvpn/client/keys 目录下生成以用户名命名的 zip 打包文件,将该压缩包下载到本地解压。 压缩包里面文件有如下,示例

.
├── ca.crt
├── username.crt
├── username.key
├── username.ovpn
└── ta.key

2、删除一个 OpenVPN 用户

修改OpenVPN 服务端配置文件

# vim /etc/openvpn/openvpn.conf
crl-verify /etc/openvpn/easy-rsa/3/pki/crl.pem

吊销用户证书,假设要吊销的用户名为 username

cd /etc/openvpn/easy-rsa/3/
./easyrsa revoke username
./easyrsa gen-crl

重启 OpenVPN 服务端使其生效

systemctl restart openvpn@server

为了方便,也将上面步骤整理成了一个脚本,可以一键删除用户: del_ovpn_user.sh:

# ! /bin/bash
set -e
OVPN_USER_KEYS_DIR=/etc/openvpn/client/keys
EASY_RSA_VERSION=3
EASY_RSA_DIR=/etc/openvpn/easy-rsa/
for user in "$@"
do
  cd $EASY_RSA_DIR/$EASY_RSA_VERSION
  echo -e 'yes\n' | ./easyrsa revoke $user
  ./easyrsa gen-crl
  # 吊销掉证书后清理客户端相关文件
  if [ -d "$OVPN_USER_KEYS_DIR/$user" ]; then
    rm -rf $OVPN_USER_KEYS_DIR/${user}*
  fi
  systemctl restart openvpn@server
done
exit 0

2、使用MySQL做登录认证

1、配置数据库

安装过程略

# 创建数据库
> CREATE DATABASE IF NOT EXISTS openvpn DEFAULT CHARSET utf8;
# 创建切换数据库
> use openvpn;
Database changed
# 创建用户表
> create table vpnuser(name char(100)not null,password char(255)default null,active int(10)not null default 1,primary key(name));
# 创建日志表
> create table loginlog(msg char (254),user char(100),pid char(100),host char(100),rhost char(100),time char(100));
# 创建测试用户
> insert into vpnuser (name,password) values ('test1',password('123456'));
> insert into vpnuser (name,password) values ('test2',password('654321'));
# 查看用户
# 第一列为登录vpn的用户名,第二列为登录的密码,第三列是是否被禁用,1为启用,改为0表示不能登录。
> select * from vpnuser;
+-------+-------------------------------------------+--------+
| name  | password                                  | active |
+-------+-------------------------------------------+--------+
| test1 | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |      1 |
| test2 | *2A032F7C5BA932872F0F045E0CF6B53CF702F2C5 |      1 |
+-------+-------------------------------------------+--------+
2 rows in set (0.00 sec)

2、配置认证

安装认证软件

rpm -Uvh http://www.nosuchhost.net/~cheese/fedora/packages/epel-7/x86_64/cheese-release-7-1.noarch.rpm
yum -y install pam_krb5 pam pam_devel gcc gcc-c++ cyrus-sasl autoconf
rpm -ivh http://repo.iotti.biz/CentOS/7/x86_64/pam_mysql-0.8.1-0.22.el7.lux.x86_64.rpm
systemctl enable saslauthd
systemctl restart saslauthd
ls /usr/lib64/security/pam_mysql.so

配置认证文件,记得修改数据库连接内容

$ cat > /etc/pam.d/openvpn_mysql << EOF
auth sufficient pam_mysql.so user=用户名 passwd=密码 host=数据库连接地址 db=openvpn table=vpnuser usercolumn=name passwdcolumn=password [where=vpnuser.active=1] sqllog=0 crypt=2 sqllog=true logtable=loginlog logmsgcolumn=msg logusercolumn=user logpidcolumn=pid loghostcolumn=host logrhostcolumn=rhost logtimecolumn=time
account required pam_mysql.so user=用户名 passwd=密码 host=数据库连接地址 db=openvpn table=vpnuser usercolumn=name passwdcolumn=password [where=vpnuser.active=1] sqllog=0 crypt=2 sqllog=true logtable=loginlog logmsgcolumn=msg logusercolumn=user logpidcolumn=pid loghostcolumn=host logrhostcolumn=rhost logtimecolumn=time
EOF

注意:此处引用的 pam_mysql.so,默认路径为 /usr/lib64/security/pam_mysql.so,此处也可以用绝对路径引用。

命令行验证

# testsaslauthd -u test1 -p 123456 -s openvpn_mysql
0: OK "Success."
  • 如果返回 0: OK "Success."则说明认证成功。
  • 如果返回:connect() : No such file or directory,那么重启一下 saslauthd服务之后再进行验证。

安装 openVPN 依赖库。

# 基于mysql进行认证,openvpn.conf配置文件取消这行注释
plugin      /etc/openvpn/openvpn-plugin-auth-pam.so openvpn_mysql

这行配置的意思是,启用插件,通过 /etc/openvpn/openvpn-plugin-auth-pam.so这个模块儿实现,并对接 saslauthd管理的 openvpn_mysql

现在还缺少 /etc/openvpn/openvpn-plugin-auth-pam.so这个模块,此模块需要通过 openVPN 的源码编译得来。

# 下载对应版本的源码包
wget http://swupdate.openvpn.org/community/releases/openvpn-2.4.12.tar.gz
# 解压
tar xf openvpn-2.4.12.tar.gz
cd openvpn-2.4.12/
# 安装编译所需依赖
yum -y install openssl openssl-devel lzo-devel
# 在根目录进行编译
./configure
make
# 将编译生成的库文件拷贝到对应目录
cp src/plugins/auth-pam/.libs/openvpn-plugin-auth-pam.so  /etc/openvpn/

拷贝完成之后,即可重启 openVPN

systemctl restart openvpn@server

3、用户管理

基于 MySQL 进行用户管理之后就非常简便了,如果需要新增用户,只需要在 user 表新增一条数据即可,如果此用户离职了,那么只需要删除这条数据即可。

分别从云服务器下载,放到C:\Program Files\OpenVPN\config目录下

/etc/openvpn/easy-rsa/pki/ca.crt 
/etc/openvpn/easy-rsa/pki/private/client.key
/etc/openvpn/easy-rsa/pki/issued/client.crt
/etc/openvpn/easy-rsa/ta.key

客户端配置

这次客户端配置,可以直接定义好,然后所有人通用此配置,只不过在登陆的时候,再使用自己的用户名密码进行认证即可。

# cat testvpn.ovpn
client
dev tun
proto udp
sndbuf 0
rcvbuf 0
remote myvpnserver 1194			# 你的服务器IP
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
comp-lzo
verb 3
cipher AES-256-CBC
auth-user-pass
auth-nocache
script-security 3
key-direction 1
ca ca.crt               # 指定CA证书的文件路径
cert client.crt         # 指定当前客户端的证书文件路径
key client.key          # 指定当前客户端的私钥文件路径
tls-crypt ta.key 1

重启服务

systemctl restart openvpn@server
systemctl enable openvpn@server

3、使用LDAP做登录认证

1、修改openvpn配置文件

plugin /usr/lib64/openvpn/plugin/lib/openvpn-auth-ldap.so "/etc/openvpn/auth/ldap.conf"			# 取消注释

2、配置LDAP认证

# vim /etc/openvpn/auth/ldap.conf
<LDAP>
	URL			ldap://127.0.0.1:11389					# 默认端口389不显示,自定义可自行修改
	BindDN		cn=admin,dc=example,dc=com
	Password	123456789.
	Timeout		15
	TLSEnable	no
	FollowReferrals no
</LDAP>
<Authorization>
	BaseDN		"ou=people,dc=example,dc=com"
	SearchFilter	"(&(cn=%u)(objectClass=person)(memberof=cn=openvpn,ou=group,dc=example,dc=com))"
	RequireGroup	false
	<Group>
		BaseDN		"ou=groups,dc=examlpe,dc=com"
		SearchFilter	"(cn=openvpn)"
		MemberAttribute	member
	</Group>
</Authorization>

重启服务

systemctl restart openvpn@server
systemctl enable openvpn@server

3、客户端配置

分别从云服务器下载,放到C:\Program Files\OpenVPN\config目录下

/etc/openvpn/easy-rsa/pki/ca.crt 
/etc/openvpn/easy-rsa/pki/private/client.key
/etc/openvpn/easy-rsa/pki/issued/client.crt
/etc/openvpn/easy-rsa/ta.key

创建配置文件

client
dev tun
proto udp
sndbuf 0
rcvbuf 0
remote openvpnserver 1194
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
comp-lzo
verb 3
cipher AES-256-CBC
script-security 3
key-direction 1
ca ca.crt
cert client.crt
key client.key
tls-crypt ta.key 1
auth-nocache
auth-user-pass

五、配置非全局代理

OpenVPN 默认是全局代理,并没有一些代理软件自带的PAC模式,这样VPN隧道连接成功后会自动增加路由条目,并且把网关地址设置成VPN的地址,不管什么流量,他都会转发到代理服务器上,通过VPN来传送。这样就会一是造成办公环境网络复杂;二是代理服务器流入流出流量大幅度增多,造成不必要的费用,因为OpenVPN 默认开机自动启动,而且会自动连接。

因此,我们需要手动设置路由记录。

1、参数介绍

1、route-nopull

当客户端加入这个参数后,openvpn 连接后不会请求远端路由表,就不会添加任何一条路由到本地路由表中。也就是不会有任何网络请求走OpenVPN 。相当于仅获取 IP 地址。

2、vpn_gateway

当客户端加入 route-nopull 后,因为没有路由表信息,所以没有出接口路由。但是我们可通过添加 route 记录和 vpn_gateway 参数使部分 IP 访问走 OpenVPN。

route   IP段          子网掩码        vpn_gateway
route   192.168.1.0   255.255.0.0     vpn_gateway
route   172.121.0.0   255.255.0.0     vpn_gateway

3、net_gateway

这个参数和 vpn_gateway 相反,在默认出去的访问全部走 Openvpn 时,强制部分 IP 访问不通过 OpenVPN 代理。

route   IP段          子网掩码      net_gateway
route   172.121.0.0   255.255.0.0   net_gateway

4、max-routes

该参数表示可以添加路由的条数,OpenVPN 默认只允许添加100条路由,如果需要添加的路由数少于100可不加这个参数。

max-routes 1000

2、服务端配置

注释以下配置

# 这条命令可以重定向客户端的网关,在进行翻墙时会使用到
# push "redirect-gateway def1 bypass-dhcp"
# 向客户端推送的路由信息,如下内容表示客户端连接之后与当前互通
# push "route 192.168.0.0 255.255.255.0" 
# push "route 10.0.0.0 255.255.0.0"
# 向客户端推送的DNS信息
# push "dhcp-option DNS 223.5.5.5"
# push "dhcp-option DNS 223.6.6.6"
# push "dhcp-option DNS 114.114.114.114"

3、客户端配置

添加以下配置

route-nopull
route 192.168.0.0 255.255.255.0 vpn_gateway		# 根据情况自行添加需要访问的网段

六、Openvpn 的内联文件

为了简化客户端配置文件的管理,OpenVPN 提供了一种便捷的内联文件方式,允许用户将根证书(ca.crt)、客户端证书(client.crt)以及客户端私钥(client.key)等必要文件直接嵌入到配置文件中。通过这种方式,用户无需分别管理多个文件,从而提高了配置的便捷性和安全性。 具体来说,用户可以在OpenVPN的配置文件(通常是.ovpn文件)中,通过特定的指令将这些证书和密钥文件的内容直接包含进来。这样,当配置文件被加载时,OpenVPN会自动读取并应用这些内联的证书和密钥信息,无需用户手动指定证书和密钥文件的路径。 这种方法不仅使得文件管理更为集中和高效,而且也减少了配置错误的可能性,因为所有的信息都在一个地方,用户只需维护一个配置文件即可。这对于用户来说是一个很大的便利,特别是对于那些需要频繁部署和更新VPN配置的场景。

实现方式举例

client
dev tun
proto udp
sndbuf 0
rcvbuf 0
remote openvpnserver 1194
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
comp-lzo
verb 3
cipher AES-256-CBC
script-security 3
key-direction 1
auth-nocache
auth-user-pass

# ca ca.crt
<ca>
-----BEGIN CERTIFICATE-----
......
......
......
-----END CERTIFICATE-----
</ca>

# cert client.crt
<cert>
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            89:53:31:72:cf:04:52:82:fb:e9:53:fe:82:fc:13:25
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: CN=192.168.1.10
        Validity
            Not Before: Nov 14 03:32:32 2023 GMT
            Not After : Feb 16 03:32:32 2026 GMT
        Subject: CN=client
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    ......
                    ......
                    ......
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            X509v3 Subject Key Identifier: 
                6E:0A:D2:EF:CE:55:4F:56:C7:57:D1:77:37:0D:AD:28:EF:A2:C8:41
            X509v3 Authority Key Identifier: 
                keyid:1A:CE:DD:A8:65:0E:3D:32:E0:74:17:15:5D:F7:6E:3B:7D:C1:59:05
                DirName:/CN=192.168.1.10
                serial:D8:A8:9B:71:84:77:C8:9B

            X509v3 Extended Key Usage: 
                TLS Web Client Authentication
            X509v3 Key Usage: 
                Digital Signature
            Netscape Comment: 
                Easy-RSA (3.0.8) Generated Certificate
            Netscape Cert Type: 
                SSL Client
    Signature Algorithm: sha256WithRSAEncryption
                    ......
                    ......
                    ......
-----BEGIN CERTIFICATE-----
......
......
......
-----END CERTIFICATE-----
</cert>

# key client.key
<key>
-----BEGIN PRIVATE KEY-----
......
......
......
-----END PRIVATE KEY-----
</key>

# tls-crypt ta.key 1
<tls-crypt>
#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
......
......
......
-----END OpenVPN Static key V1-----
</tls-crypt>
0

评论区