CentOS 7 安装openvpn详解

VPN的用途不用多说。相信大家已然清楚;本次安装openvpn是基于centos7的环境;安装前务必关掉SELinux与Firewalld,本篇中将使用iptables来进行演示;

一、查看openvpn版本及安装:如无法获取软件请自行更新yum仓库;

二、安装easy-rsa3来生成openvpn所需证书;easy-rsa3用来制作ca证书、服务端证书、客户端证书等;

1、在/etc/openvpn目录下创建easy-rsa目录并进入;
mkdir /etc/openvpn/easy-rsa && cd /etc/openvpn/easy-rsa

2、拷贝easy-rsa执行文件与vars.example到/etc/openvpn/easy-rsa目录下;
cp -r /usr/share/easy-rsa/3.0.3/* /etc/openvpn/easy-rsa/
cp /usr/share/doc/easy-rsa-3.0.3/vars.example ./vars

3、修改vars中的以下字段,完成后保存退出;
set_var EASYRSA_REQ_COUNTRY     "CN"
set_var EASYRSA_REQ_PROVINCE    "Beijing"
set_var EASYRSA_REQ_CITY        "Beijing"
set_var EASYRSA_REQ_ORG         "optaim.com"
set_var EASYRSA_REQ_EMAIL       "[email protected]"
set_var EASYRSA_REQ_OU          "Optaim"

三、创建openvpn服务端证书及KEY

1、进行/etc/openvpn/easy-rsa目录并执行以下命令进行初始化;
./easy-rsa init-pki

[root@ops-slave easy-rsa]# ./easyrsa init-pki

Note: using Easy-RSA configuration from: ./vars

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /etc/openvpn/easy-rsa/pki
2、创建ca证书;
./easyrsa build-ca

[root@ops-slave easy-rsa]# ./easyrsa build-ca

Note: using Easy-RSA configuration from: ./vars
Generating a 2048 bit RSA private key
...........................................................................................................................................+++
....+++
writing new private key to '/etc/openvpn/easy-rsa/pki/private/ca.key.ly31KfClee'
Enter PEM pass phrase:                              # 输入密码,我的密码123456
Verifying - Enter PEM pass phrase:                  # 再次输入
-----
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                 # 证书位置;

注意:在要求输入PEM密码:Enter PEM pass phrase处输入的密码必须记住,不然以后不能为证书签名。

3、创建服务端证书;
./easyrsa gen-req server nopass

[root@ops-slave easy-rsa]# ./easyrsa gen-req server nopass

Note: using Easy-RSA configuration from: ./vars
Generating a 2048 bit RSA private key
............................+++
..........+++
writing new private key to '/etc/openvpn/easy-rsa/pki/private/server.key.zpvNtZmCsj'
-----
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           # 密钥位置
4、签署服务端证书;
./easyrsa sign server server

[root@ops-slave easy-rsa]# ./easyrsa sign server server

Note: using Easy-RSA configuration from: ./vars


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 3650 days:

subject=
commonName = server


Type the word 'yes' to continue, or any other input to abort.
Confirm request details: yes                  # 输入yes
Using configuration from ./openssl-1.0.cnf
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:      # 输入上面ca证书生成时的密码;123456
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 May 3 08:01:29 2029 GMT (3650 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /etc/openvpn/easy-rsa/pki/issued/server.crt        #证书位置
5、DH证书生成          # 生成Diffie-Hellman,大约几分钟;
./easyrsa gen-dh

[root@ops-slave easy-rsa]# ./easyrsa gen-dh

Note: using Easy-RSA configuration from: ./vars
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
.................................................................................................................................+................+..............................................................................
...+.........................+..................+......................................................................................+.........................................................................................
......................................................................................+................................................................................+.........................................................
..........................................................................................................................................................................+.....................+................................
.................................................................................................................................................................................................................................
.......................+.....................+...................................................................................................................................................................................
..............................................................................................+...................................................................................................+..............................
..+..............................................................................................................................................................................................................................
...........................+..........+.....+...............................+.+.......................................................................................................................+..........................
....................................................................+..........................................................................+.................................................................................
..............................................................+...........................................................+...............................................................+......................................
.................................................................................................................................................................................................................................
.+..........................................................................................................................................................+..........++*++*

DH parameters of size 2048 created at /etc/openvpn/easy-rsa/pki/dh.pem
6、生成ta密钥;
openvpn --genkey --secret ta.key

四、创建客户端证书;

在openvpn目录下创建easy-client目录;与easy-rsa服务器证书目录进行区别;

1、创建目录并初始化;
[root@ops-slave ~]# mkdir /etc/openvpn/client
[root@ops-slave ~]# cd /etc/openvpn/client
[root@ops-slave client]# cp -r /usr/share/easy-rsa/3.0.3/* .
[root@ops-slave client]# cp /usr/share/doc/easy-rsa-3.0.3/vars.example ./vars

[root@ops-slave client]# ./easyrsa init-pki

Note: using Easy-RSA configuration from: ./vars

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /etc/openvpn/client/pki
2、生成client证书;
[root@ops-slave client]# ./easyrsa gen-req client nopass

Note: using Easy-RSA configuration from: ./vars
Generating a 2048 bit RSA private key
.......................+++
.+++
writing new private key to '/etc/openvpn/client/pki/private/client.key.tVmgVuniE4'
-----
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/client/pki/reqs/client.req
key: /etc/openvpn/client/pki/private/client.key         # 客户端证书路径
3、对客户端证书进行签约;
cd /etc/openvpn/easy-rsa      # 进入easy-rsa目录下;
./easyrsa import-req /etc/openvpn/client/pki/reqs/client.req client

[root@ops-slave easy-rsa]# ./easyrsa import-req /etc/openvpn/client/pki/reqs/client.req client

Note: using Easy-RSA configuration from: ./vars

The request has been successfully imported with a short name of: client
You may now use this name to perform signing operations on this request.

[root@ops-slave easy-rsa]# ./easyrsa sign client client       #第一个client表示客户端,第二个client表示导入上面生成的客户端证书名称;

Note: using Easy-RSA configuration from: ./vars


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 3650 days:

subject=
    commonName                = client


Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: yes
Using configuration from ./openssl-1.0.cnf
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:     # 输入密码123456
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 May  3 09:17:50 2029 GMT (3650 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /etc/openvpn/easy-rsa/pki/issued/client.crt     # 客户端证书路径

五、将生成的密钥进行集中存储。并且修改server.conf配置文件指向密钥的路径;

1、创建密钥存储目录及密钥的拷贝;
[root@ops-slave openvpn]# mkdir /etc/openvpn/keys
[root@ops-slave openvpn]# cp /etc/openvpn/easy-rsa/pki/ca.crt /etc/openvpn/keys/
[root@ops-slave openvpn]# cp /etc/openvpn/easy-rsa/pki/private/server.key /etc/openvpn/keys/
[root@ops-slave openvpn]# cp /etc/openvpn/easy-rsa/pki/issued/server.crt /etc/openvpn/keys/
[root@ops-slave openvpn]# cp /etc/openvpn/easy-rsa/pki/dh.pem /etc/openvpn/keys/
2、配置openvpn目录下server.conf文件;
[root@ops-slave openvpn]# cat server.conf
port        1194
proto       udp
dev         tun
ca          /etc/openvpn/keys/ca.crt
cert        /etc/openvpn/keys/server.crt
key         /etc/openvpn/keys/server.key
dh          /etc/openvpn/keys/dh.pem
server      172.16.0.0 255.255.0.0                # 为客户端分配的用于接入openvpn服务器的地址段;

push "route 10.10.0.0 255.255.0.0"              # 此项为客户端路由;

log-append         /var/log/openvpn/openvpn.log
status             /var/log/openvpn/openvpn-status.log
keepalive   10 120
verb        3
client-config-dir /etc/openvpn/ccd            # 开启权限分配功能;
client-to-client
comp-lzo
persist-key
persist-tun

#########auth password########
script-security 3               ###--加入脚本处理,如用密码验证
auth-user-pass-verify /etc/openvpn/checkpwd.sh via-env ###指定只用的认证脚本
client-cert-not-required        #####不请求客户的CA证书,使用User/Pass验证,如果同时启用证书和密码认证,注释掉该行
username-as-common-name         ### 使用客户提供的UserName作为Common Name
3、配置防火墙转发功能; 
[root@ops-slave openvpn]# cat /etc/sysconfig/iptables.save
# Generated by iptables-save v1.4.21 on Thu Apr 25 17:51:13 2019
*nat
:PREROUTING ACCEPT [2331079:168210339]
:POSTROUTING ACCEPT [408:33496]
:OUTPUT ACCEPT [1271:89120]
-A POSTROUTING -s 10.10.0.0/16 -o eth0 -j SNAT --to-source 10.10.138.72
-A POSTROUTING -s 172.16.0.0/16 -j SNAT --to-source 10.10.138.72
COMMIT
# Completed on Thu Apr 25 17:51:13 2019
# Generated by iptables-save v1.4.21 on Thu Apr 25 17:51:13 2019
*filter
COMMIT
# Completed on Thu Apr 25 17:51:13 2019
4、开启服务器转发;
[root@ops-slave openvpn]# cat /etc/sysctl.conf
# sysctl settings are defined through files in
# /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/.
#
# Vendors settings live in /usr/lib/sysctl.d/.
# To override a whole file, create a new file with the same in
# /etc/sysctl.d/ and put new settings there. To override
# only specific settings, add a file with a lexically later
# name in /etc/sysctl.d/ and put new settings there.
#
# For more information, see sysctl.conf(5) and sysctl.d(5).

net.ipv4.ip_forward = 1            # 使其等1为开启状态;

保存退出
[root@ops-slave openvpn]# sysctl -p      #使用配置生效;
5、增加肢本认认证文件checkpwd.sh;
[root@ops-slave openvpn]# cat checkpwd.sh
#!/bin/sh
###########################################################
# checkpsw.sh (C) 2004 Mathias Sundman <[email protected]>
#
# This script will authenticate OpenVPN users against
# a plain text file. The passfile should simply contain
# one row per user with the username first followed by
# one or more space(s) or tab(s) and then the password.


PASSFILE="/etc/openvpn/psw-file"
LOG_FILE="/var/log/openvpn-password.log"
TIME_STAMP=`date "+%Y-%m-%d %T"`

###########################################################

if [ ! -r "${PASSFILE}" ]; then
echo "${TIME_STAMP}: Could not open password file \"${PASSFILE}\" for reading." >> ${LOG_FILE}
exit 1
fi

CORRECT_PASSWORD=`awk '!/^;/&&!/^#/&&$1=="'${username}'"{print $2;exit}' ${PASSFILE}`

if [ "${CORRECT_PASSWORD}" = "" ]; then
echo "${TIME_STAMP}: User does not exist: username=\"${username}\", password=\"${password}\"." >> ${LOG_FILE}
exit 1
fi

if [ "${password}" = "${CORRECT_PASSWORD}" ]; then
echo "${TIME_STAMP}: Successful authentication: username=\"${username}\"." >> ${LOG_FILE}
exit 0
fi

echo "${TIME_STAMP}: Incorrect password: username=\"${username}\", password=\"${password}\"." >> ${LOG_FILE}
exit 1
6、根据checkpwd.sh中"PASSFILE“路径增加psw-file文件用于openvpn客户端登录;
[root@ops-slave openvpn]# cat psw-file
test  123123                   # 客户端用户名为:test,密码为:123123
7、启动openvpn服务;
systemctl start openvpn

首次启动会报错:
Failed to restart openvpn.service: Unit not found

手动创建openvpn启动文件,如下所示;
[root@ops
-slave openvpn]# cat /lib/systemd/system/openvpn.service [Unit] Description=OpenVPN Robust And Highly Flexible Tunneling Application On %I After=network.target [Service] PrivateTmp=false Type=forking PIDFile=/var/run/openvpn/%i.pid ExecStart=/usr/sbin/openvpn --daemon --writepid /var/run/openvpn/%i.pid --cd /etc/openvpn/ --config server.conf [Install] WantedBy=multi-user.target 保存退出后重启即可;
8、使防火墙生效;
systemctl restart iptables

CentOS 7 下建议使用iptables,关闭Firewalld, 如没有iptables可自行安装;

[root@ops-slave ~]# iptables -t nat -nvL
Chain PREROUTING (policy ACCEPT 1851K packets, 111M bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 1838K packets, 110M bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 3480K packets, 209M bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 140K packets, 8289K bytes)
 pkts bytes target     prot opt in     out     source               destination
3296K  198M SNAT       all  --  *      eth0    10.10.0.0/16         0.0.0.0/0            to:10.10.138.72
57175 3433K SNAT       all  --  *      *       172.16.0.0/16        0.0.0.0/0            to:10.10.138.72

六、客户端配置;

windows与mac下载对应的客户端软件并安装;相信对于做技术的你我来说比较简单。这里不做过多演示。如有失败者可留言与我;

1、在服务器上面进入/etc/openvpn目录下; 拷贝client密钥;
cd /etc/openvpn/
cp easy-rsa/pki/ca.crt /root/
cp easy-rsa/pki/issued/client.crt /root/
cp client/pki/private/client.key /root/
cp /usr/share/doc/openvpn-2.4.7/sample/sample-config-files/client.conf /root/client.ovpn

将以上ca.crt、client.crt、client.key、client.ovpn放入到mac电脑的同一目录下;如果是windows电脑放在openvpn客户端的安装目录下config中。如:C:\Program Files\OpenVPN\config下;
2、修改客户端配置文件;
client
dev tun
proto udp
remote my-server-1 1194         #my-server-1 为openvpn的外网ip地址,将其替换为你自己的openvpn服务器的外网地址;
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt                         #此为证书。尽量放在同一目录下。保持默认即可;
cert client.crt                  #此为证书。尽量放在同一目录下。保持默认即可;
key client.key                 #此为证书。尽量放在同一目录下。保持默认即可;
route-method exe
route-delay 2
verb 3
comp-lzo
auth-user-pass

mac上面安装完成后首次运行会出现下图;点击我有配置文件;

点击确定;

点击此图标。下拉菜单中选择VPN详情;

 

将client.ovpn拖到上图左边窗口; 然后点击连接;

 

输入服务器中配置的用户名密码;

t

此时已连接成功;可ping下远程地址内网ip是否可通;

连接vpn前:

连接vpn后:

猜你喜欢

转载自www.cnblogs.com/hsggj/p/10820115.html