阿里云OpenVPN部署实战

Posted y_zilong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了阿里云OpenVPN部署实战相关的知识,希望对你有一定的参考价值。

1、准备环境

(1)准备三台阿里云,一台作为openvpn服务端,两台作为模拟公司内网web

 

(2) 修改网络防火墙规则

(3)三台主机实现基于密钥的登录方式

[root@openvpn ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:07KkWsTnDClOrH05ir8x7SGFSPZvvVKD+kzmUh2D1NQ root@openvpn.yzil.xyz
The key's randomart image is:
+---[RSA 3072]----+
|       o..       |
|      . . E      |
|  o  . .         |
| o + o..o.       |
|  . * *oSo.      |
|   = *oX++       |
|  . *o&.=.       |
|   .o/.o .       |
|  ..=+=..        |
+----[SHA256]-----+
[root@openvpn ~]# ssh-copy-id 127.0.0.1
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:8iMKDxZD04lB3uX4Q/R7pPNkkaH9xzCy0hsWUYJDdFQ.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@127.0.0.1's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '127.0.0.1'"
and check to make sure that only the key(s) you wanted were added.

[root@openvpn ~]# cd .ssh
[root@openvpn .ssh]# ls
authorized_keys  id_rsa  id_rsa.pub  known_hosts
[root@openvpn .ssh]# cd
[root@openvpn ~]# rsync -av .ssh 172.30.0.10:/root/
root@172.30.0.10's password: 
sending incremental file list
.ssh/
.ssh/authorized_keys
.ssh/id_rsa
.ssh/id_rsa.pub
.ssh/known_hosts

sent 4,446 bytes  received 96 bytes  605.60 bytes/sec
total size is 4,104  speedup is 0.90
[root@openvpn ~]# rsync -av .ssh 172.30.0.20:/root/
The authenticity of host '172.30.0.20 (172.30.0.20)' can't be established.
ECDSA key fingerprint is SHA256:A/Lpzefk7KjjkxUCncz+iBTzR3wZT+cpTRE2SGmWigI.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '172.30.0.20' (ECDSA) to the list of known hosts.
root@172.30.0.20's password: 
sending incremental file list
.ssh/
.ssh/authorized_keys
.ssh/id_rsa
.ssh/id_rsa.pub
.ssh/known_hosts

sent 4,619 bytes  received 96 bytes  496.32 bytes/sec
total size is 4,277  speedup is 0.91
[root@openvpn ~]# ssh 172.30.0.10

Welcome to Alibaba Cloud Elastic Compute Service !

Activate the web console with: systemctl enable --now cockpit.socket

Last login: Tue May 11 09:20:19 2021 from 172.30.0.1
[root@web01 ~]# ssh 172.30.0.20
The authenticity of host '172.30.0.20 (172.30.0.20)' can't be established.
ECDSA key fingerprint is SHA256:A/Lpzefk7KjjkxUCncz+iBTzR3wZT+cpTRE2SGmWigI.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '172.30.0.20' (ECDSA) to the list of known hosts.

Welcome to Alibaba Cloud Elastic Compute Service !

Activate the web console with: systemctl enable --now cockpit.socket

[root@web02 ~]# 

2、安装OpenVPN

(1)安装OpenVPN和证书工具

#OpenVPN服务器端
[root@openvpn ~]# yum -y install openvpn
#证书管理工具
[root@openvpn ~]# yum -y install easy-rsa

       # 查看包中相关文件

[root@openvpn ~]# rpm -qi openvpn easy-rsa

[root@openvpn ~]# rpm -ql openvpn

[root@openvpn ~]# rpm -ql easy-rsa

(2)准备相关配置文件

#生成服务器配置文件
[root@openvpn ~]# cp /usr/share/doc/openvpn/sample/sample-config-files/server.conf /etc/openvpn/

#准备证书签发相关文件
[root@openvpn ~]# cp -r /usr/share/easy-rsa/ /etc/openvpn/easy-rsa-server

#准备签发证书相关变量的配置文件
[root@openvpn ~]# cp /usr/share/doc/easy-rsa/vars.example /etc/openvpn/easy-rsa-server/3/vars

#建议修改给CA和OpenVPN服务器颁发的证书的有效期,可适当加长
[root@openvpn ~]# vim /etc/openvpn/easy-rsa-server/3/vars
#CA的证书有效期默认为10年,可以适当延长,比如:36500天
#set_var EASYRSA_CA_EXPIRE      3650
#将上面修改为下面
set_var EASYRSA_CA_EXPIPE  36500

#服务器证书默认为825天,可适当加长,比如:3650天
#set_var EASYRSA_CERT_EXPIRE    825
set_var EASYRSA_CERT_EXPIPE  3650

[root@openvpn ~]# tree /etc/openvpn/
/etc/openvpn/
├── client
├── easy-rsa-server
│   ├── 3 -> 3.0.8
│   ├── 3.0 -> 3.0.8
│   └── 3.0.8
│       ├── easyrsa
│       ├── openssl-easyrsa.cnf
│       ├── vars
│       └── x509-types
│           ├── ca
│           ├── client
│           ├── code-signing
│           ├── COMMON
│           ├── email
│           ├── kdc
│           ├── server
│           └── serverClient
├── server
└── server.conf

7 directories, 12 files
[root@openvpn ~]# 

3、准备证书相关文件

脚本easyrsa帮助用法

[root@openvpn ~]# cd /etc/openvpn/easy-rsa-server/3/
[root@openvpn 3]# pwd
/etc/openvpn/easy-rsa-server/3
[root@openvpn 3]# file ./easyrsa 
./easyrsa: POSIX shell script, ASCII text executable
[root@openvpn 3]# ./easyrsa 

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

Easy-RSA 3 usage and overview

USAGE: easyrsa [options] COMMAND [command-options]

A list of commands is shown below. To get detailed usage and help for a
command, run:
  ./easyrsa help COMMAND

For a listing of options that can be supplied before the command, use:
  ./easyrsa help options

Here is the list of commands available with a short syntax reminder. Use the
'help' command above to get full usage details.

  init-pki
  build-ca [ cmd-opts ]
  gen-dh
  gen-req <filename_base> [ cmd-opts ]
  sign-req <type> <filename_base>
  build-client-full <filename_base> [ cmd-opts ]
  build-server-full <filename_base> [ cmd-opts ]
  revoke <filename_base> [cmd-opts]
  renew <filename_base> [cmd-opts]
  build-serverClient-full <filename_base> [ cmd-opts ]
  gen-crl
  update-db
  show-req <filename_base> [ cmd-opts ]
  show-cert <filename_base> [ cmd-opts ]
  show-ca [ cmd-opts ]
  import-req <request_file_path> <short_basename>
  export-p7 <filename_base> [ cmd-opts ]
  export-p8 <filename_base> [ cmd-opts ]
  export-p12 <filename_base> [ cmd-opts ]
  set-rsa-pass <filename_base> [ cmd-opts ]
  set-ec-pass <filename_base> [ cmd-opts ]
  upgrade <type>

DIRECTORY STATUS (commands would take effect on these locations)
  EASYRSA: /etc/openvpn/easy-rsa-server/3.0.8
      PKI: /etc/openvpn/easy-rsa-server/3/pki


[root@openvpn 3]# 

(1)初始化PKI生成PKI相关目录和文件

[root@openvpn ~]# cd /etc/openvpn/easy-rsa-server/3/
[root@openvpn 3]# pwd
/etc/openvpn/easy-rsa-server/3
[root@openvpn 3]# ls
easyrsa  openssl-easyrsa.cnf  vars  x509-types

#初始化数据,在当前目录下生成pki目录及相关文件
[root@openvpn 3]# ./easyrsa init-pki

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

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


[root@openvpn 3]# tree
.
├── easyrsa
├── openssl-easyrsa.cnf
├── pki           #生成一个新目录及相关文件
│   ├── openssl-easyrsa.cnf
│   ├── private
│   ├── reqs
│   └── safessl-easyrsa.cnf
├── vars
└── x509-types
    ├── ca
    ├── client
    ├── code-signing
    ├── COMMON
    ├── email
    ├── kdc
    ├── server
    └── serverClient

4 directories, 13 files
[root@openvpn 3]# 

(2)创建CA机构

[root@openvpn ~]# cd /etc/openvpn/easy-rsa-server/3/
[root@openvpn 3]# tree pki
pki
├── openssl-easyrsa.cnf
├── private
├── reqs
└── safessl-easyrsa.cnf

2 directories, 2 files
[root@openvpn 3]# ./easyrsa build-ca nopass

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa-server/3.0.8/vars
Using SSL: openssl OpenSSL 1.1.1g FIPS  21 Apr 2020
Generating RSA private key, 2048 bit long modulus (2 primes)
...........................................................................+++++
.............................+++++
e is 65537 (0x010001)
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-server/3/pki/ca.crt    #生成自签名的证书文件


[root@openvpn 3]# tree pki
pki
├── ca.crt     #生成自签名的证书文件
├── certs_by_serial
├── index.txt
├── index.txt.attr
├── issued
├── openssl-easyrsa.cnf
├── private
│   └── ca.key    #生成私钥文件
├── renewed
│   ├── certs_by_serial
│   ├── private_by_serial
│   └── reqs_by_serial
├── reqs
├── revoked
│   ├── certs_by_serial
│   ├── private_by_serial
│   └── reqs_by_serial
├── safessl-easyrsa.cnf
└── serial

12 directories, 7 files

#生成CA相关的文件
[root@openvpn 3]# cat pki/serial 
01
[root@openvpn 3]# ll pki/index.txt
-rw------- 1 root root 0 May 11 10:08 pki/index.txt
[root@openvpn 3]# ll pki/ca.crt pki/private/ca.key 
-rw------- 1 root root 1204 May 11 10:08 pki/ca.crt
-rw------- 1 root root 1675 May 11 10:08 pki/private/ca.key


#查看生成的自签名证书
[root@openvpn 3]# cat pki/ca.crt 
-----BEGIN CERTIFICATE-----
MIIDSzCCAjOgAwIBAgIUN7JcckMA+zZnLO4BElZRJ+G85TcwDQYJKoZIhvcNAQEL
BQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMjEwNTExMDIwODEyWhcNMzEw
NTA5MDIwODEyWjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcN
AQEBBQADggEPADCCAQoCggEBAOytkgYlA6oRiqrSnEUt0wYKPryLaUMkMMQttB2B
Vowc0q7XUxfM0tg+ogb+uT6Ubzwc7cgF+KGjXpWAwQvqheQuJ1fxcLvMYM3GQIDG
lZfeLnSet+BCyzsrAjkW9Jbii10od2HJ8saZChm4rhYpamwNyb71dlK999yVLHDW
o/j1vVA5eQsTob6Y8St5ELrV8V9PYmtpzpB2uczjSbs4jXO+ZGfttoJ4e+N3qmds
KirS/eAbYr20cF7C20CG1lVeOYlZMHdcoFKHDh7bIT1VTpl1wMs1Hz4Zi1Q3GeSH
LI1A9RZx1sJf+pau35ljuYRqJzNzZjqTk0HVoxEvKuH3SEMCAwEAAaOBkDCBjTAd
BgNVHQ4EFgQURax14PPu+Uaoyjmil4duCypnFWswUQYDVR0jBEowSIAURax14PPu
+Uaoyjmil4duCypnFWuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghQ3slxy
QwD7Nmcs7gESVlEn4bzlNzAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkq
hkiG9w0BAQsFAAOCAQEAmSJWkGonJSwuahCoWbpMXGMv8ARQGgHsa1IRvp2S7l+n
X+XBZD2G8kC/m6AI8HolE99i0P2pwU2c1GtTOxMsaaq/bn9g3tYGUd+3zt157tFg
PmPaqpjahwhPDAb7FCYUUssFiYHNbjWS7Zym5qgwSipLCMtmS1SAIuHE4Fkk6w4o
BYJryzHEGM0MIqsjvuTwkmmage3K8Dco2jpluNXXfln9QpqRc7wmcvFW5x8Ots4j
khr27fAfjVM/iD7+hfFhNs/tl98M5J13SSB1Z/HxIpAjWRwSxtQI4qJogboTX4O9
FScIR7xC5kUxld5KX9sY9CH9Wdm6b6/TYIKYpzX+Sw==
-----END CERTIFICATE-----
[root@openvpn 3]# openssl x509 -in pki/ca.crt -noout -text 
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            37:b2:5c:72:43:00:fb:36:67:2c:ee:01:12:56:51:27:e1:bc:e5:37
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: CN = Easy-RSA CA
        Validity
            Not Before: May 11 02:08:12 2021 GMT
            Not After : May  9 02:08:12 2031 GMT
        Subject: CN = Easy-RSA CA
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                RSA Public-Key: (2048 bit)
                Modulus:
                    00:ec:ad:92:06:25:03:aa:11:8a:aa:d2:9c:45:2d:
                    d3:06:0a:3e:bc:8b:69:43:24:30:c4:2d:b4:1d:81:
                    56:8c:1c:d2:ae:d7:53:17:cc:d2:d8:3e:a2:06:fe:
                    b9:3e:94:6f:3c:1c:ed:c8:05:f8:a1:a3:5e:95:80:
                    c1:0b:ea:85:e4:2e:27:57:f1:70:bb:cc:60:cd:c6:
                    40:80:c6:95:97:de:2e:74:9e:b7:e0:42:cb:3b:2b:
                    02:39:16:f4:96:e2:8b:5d:28:77:61:c9:f2:c6:99:
                    0a:19:b8:ae:16:29:6a:6c:0d:c9:be:f5:76:52:bd:
                    f7:dc:95:2c:70:d6:a3:f8:f5:bd:50:39:79:0b:13:
                    a1:be:98:f1:2b:79:10:ba:d5:f1:5f:4f:62:6b:69:
                    ce:90:76:b9:cc:e3:49:bb:38:8d:73:be:64:67:ed:
                    b6:82:78:7b:e3:77:aa:67:6c:2a:2a:d2:fd:e0:1b:
                    62:bd:b4:70:5e:c2:db:40:86:d6:55:5e:39:89:59:
                    30:77:5c:a0:52:87:0e:1e:db:21:3d:55:4e:99:75:
                    c0:cb:35:1f:3e:19:8b:54:37:19:e4:87:2c:8d:40:
                    f5:16:71:d6:c2:5f:fa:96:ae:df:99:63:b9:84:6a:
                    27:33:73:66:3a:93:93:41:d5:a3:11:2f:2a:e1:f7:
                    48:43
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier: 
                45:AC:75:E0:F3:EE:F9:46:A8:CA:39:A2:97:87:6E:0B:2A:67:15:6B
            X509v3 Authority Key Identifier: 
                keyid:45:AC:75:E0:F3:EE:F9:46:A8:CA:39:A2:97:87:6E:0B:2A:67:15:6B
                DirName:/CN=Easy-RSA CA
                serial:37:B2:5C:72:43:00:FB:36:67:2C:EE:01:12:56:51:27:E1:BC:E5:37

            X509v3 Basic Constraints: 
                CA:TRUE
            X509v3 Key Usage: 
                Certificate Sign, CRL Sign
    Signature Algorithm: sha256WithRSAEncryption
         99:22:56:90:6a:27:25:2c:2e:6a:10:a8:59:ba:4c:5c:63:2f:
         f0:04:50:1a:01:ec:6b:52:11:be:9d:92:ee:5f:a7:5f:e5:c1:
         64:3d:86:f2:40:bf:9b:a0:08:f0:7a:25:13:df:62:d0:fd:a9:
         c1:4d:9c:d4:6b:53:3b:13:2c:69:aa:bf:6e:7f:60:de:d6:06:
         51:df:b7:ce:dd:79:ee:d1:60:3e:63:da:aa:98:da:87:08:4f:
         0c:06:fb:14:26:14:52:cb:05:89:81:cd:6e:35:92:ed:9c:a6:
         e6:a8:30:4a:2a:4b:08:cb:66:4b:54:80:22:e1:c4:e0:59:24:
         eb:0e:28:05:82:6b:cb:31:c4:18:cd:0c:22:ab:23:be:e4:f0:
         92:69:9a:81:ed:ca:f0:37:28:da:3a:65:b8:d5:d7:7e:59:fd:
         42:9a:91:73:bc:26:72:f1:56:e7:1f:0e:b6:ce:23:92:1a:f6:
         ed:f0:1f:8d:53:3f:88:3e:fe:85:f1:61:36:cf:ed:97:df:0c:
         e4:9d:77:49:20:75:67:f1:f1:22:90:23:59:1c:12:c6:d4:08:
         e2:a2:68:81:ba:13:5f:83:bd:15:27:08:47:bc:42:e6:45:31:
         95:de:4a:5f:db:18:f4:21:fd:59:d9:ba:6f:af:d3:60:82:98:
         a7:35:fe:4b
[root@openvpn 3]# 

(3)创建服务端的证书申请

[root@openvpn ~]# cd /etc/openvpn/easy-rsa-server/3

#创建服务器证书申请文件,其中server是文件前缀
[root@openvpn 3]# ./easyrsa gen-req server nopass

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa-server/3.0.8/vars
Using SSL: openssl OpenSSL 1.1.1g FIPS  21 Apr 2020
Generating a RSA private key
.........+++++
.......................................+++++
writing new private key to '/etc/openvpn/easy-rsa-server/3/pki/easy-rsa-26435.h8mNQH/tmp.J4zpVc'
-----
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]:openvpn   #可以默认,也可以是名字,主机名或者服务的名字

Keypair and certificate request completed. Your files are:
req: /etc/openvpn/easy-rsa-server/3/pki/reqs/server.req       #生成请求文件
key: /etc/openvpn/easy-rsa-server/3/pki/private/server.key    #生成私钥文件


[root@openvpn 3]# tree pki
pki
├── ca.crt
├── certs_by_serial
├── index.txt
├── index.txt.attr
├── issued
├── openssl-easyrsa.cnf
├── private
│   ├── ca.key
│   └── server.key    #生成私钥文件
├── renewed
│   ├── certs_by_serial
│   ├── private_by_serial
│   └── reqs_by_serial
├── reqs
│   └── server.req    #生成请求文件
├── revoked
│   ├── certs_by_serial
│   ├── private_by_serial
│   └── reqs_by_serial
├── safessl-easyrsa.cnf
└── serial

12 directories, 9 files
[root@openvpn 3]# 

(4) 颁发服务端证书

#查看颁发证书命令用法
[root@openvpn ~]# cd /etc/openvpn/easy-rsa-server/3
[root@openvpn 3]# ./easyrsa help sign

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

  sign-req <type> <filename_base>
      Sign a certificate request of the defined type. <type> must be a known
      type such as 'client', 'server', 'serverClient', or 'ca' (or a user-added type.)

      This request file must exist in the reqs/ dir and have a .req file
      extension. See import-req below for importing reqs from other sources.

[root@openvpn 3]# 
[root@openvpn ~]# cd /etc/openvpn/easy-rsa-server/3

#将上面server.req的申请,颁发server类型的证书
[root@openvpn 3]# ./easyrsa sign server server

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa-server/3.0.8/vars
Using SSL: openssl OpenSSL 1.1.1g FIPS  21 Apr 2020


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:   #可以看到vars文件指定的有效期

subject=
    commonName                = openvpn


Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: yes    #输入yes回车
Using configuration from /etc/openvpn/easy-rsa-server/3/pki/easy-rsa-26477.JjDWEL/tmp.fvRTvE
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'openvpn'
Certificate is to be certified until Aug 14 02:39:06 2023 GMT (825 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /etc/openvpn/easy-rsa-server/3/pki/issued/server.crt  #生成服务器证书文件


[root@openvpn 3]# tree
.
├── easyrsa
├── openssl-easyrsa.cnf
├── pki
│   ├── ca.crt
│   ├── certs_by_serial
│   │   └── 1AFDE5F5F9FB134A0BB736AF2AC373FE.pem   #服务器证书文件
│   ├── index.txt
│   ├── index.txt.attr
│   ├── index.txt.attr.old
│   ├── index.txt.old
│   ├── issued
│   │   └── server.crt           #服务器证书文件
│   ├── openssl-easyrsa.cnf
│   ├── private
│   │   ├── ca.key
│   │   └── server.key
│   ├── renewed
│   │   ├── certs_by_serial
│   │   ├── private_by_serial
│   │   └── reqs_by_serial
│   ├── reqs
│   │   └── server.req
│   ├── revoked
│   │   ├── certs_by_serial
│   │   ├── private_by_serial
│   │   └── reqs_by_serial
│   ├── safessl-easyrsa.cnf
│   ├── serial
│   └── serial.old
├── vars
└── x509-types
    ├── ca
    ├── client
    ├── code-signing
    ├── COMMON
    ├── email
    ├── kdc
    ├── server
    └── serverClient

14 directories, 25 files

[root@openvpn 3]# diff pki/certs_by_serial/1AFDE5F5F9FB134A0BB736AF2AC373FE.pem pki/issued/server.crt 
[root@openvpn 3]# ll !*
ll pki/certs_by_serial/1AFDE5F5F9FB134A0BB736AF2AC373FE.pem pki/issued/server.crt
-rw------- 1 root root 4614 May 11 10:39 pki/certs_by_serial/1AFDE5F5F9FB134A0BB736AF2AC373FE.pem
-rw------- 1 root root 4614 May 11 10:39 pki/issued/server.crt
[root@openvpn 3]# 

4、创建Diffie-Hellman密钥

[root@openvpn ~]# cd /etc/openvpn/easy-rsa-server/3
[root@openvpn 3]# pwd
/etc/openvpn/easy-rsa-server/3
[root@openvpn 3]# ./easyrsa gen-dh

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa-server/3.0.8/vars
Using SSL: openssl OpenSSL 1.1.1g FIPS  21 Apr 2020
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-server/3/pki/dh.pem

#查看生成的文件
[root@openvpn 3]# ll pki/dh.pem 
-rw------- 1 root root 424 May 11 13:23 pki/dh.pem
[root@openvpn 3]# cat pki/dh.pem 
-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEAmt6L6Cm3oW0unw6RkFEZ0ENf7Hjq+eoLxf+xRIseCWUkjdJ0lz89
DD0zZ0UbcayrOR7gtsUtrnkPdeyncIL0TWjAMq5voBprXLY3guneKCPcFxxEHS3D
m0sWpggNtR16eSP9M9k9rqauLX0zJ1ycoR+EtykH9dnLLGR7sQYjiKb2BX6MZs69
IoJaQUSZh9F4672W0hrKYeJEtiRXW6YHl36jcrv3RrDGbu2O0YzdOlqu3BEpM1vR
hs31ZxS2rEbLFneXZjQEH6UmWwxxOPwdFZcj1yp/z/lJWjDNACAbe422KMIcEsxf
pLjzT9wVx7UpUyTQ152AeDubtJaqvFZJowIBAg==
-----END DH PARAMETERS-----
[root@openvpn 3]# 

5、将CA和服务器证书相关文件复制到服务器相应的目录

[root@openvpn ~]# mkdir /etc/openvpn/certs
[root@openvpn ~]# cp /etc/openvpn/easy-rsa-server/3/pki/ca.crt /etc/openvpn/certs/
[root@openvpn ~]# cp /etc/openvpn/easy-rsa-server/3/pki/issued/server.crt /etc/openvpn/certs/
[root@openvpn ~]# cp /etc/openvpn/easy-rsa-server/3/pki/private/server.key /etc/openvpn/certs/
[root@openvpn ~]# cp /etc/openvpn/easy-rsa-server/3/pki/dh.pem /etc/openvpn/certs/
[root@openvpn ~]# ll /etc/openvpn/certs/
total 20
-rw------- 1 root root 1204 May 11 11:43 ca.crt
-rw------- 1 root root  424 May 11 13:26 dh.pem
-rw------- 1 root root 4614 May 11 11:43 server.crt
-rw------- 1 root root 1708 May 11 11:44 server.key
[root@openvpn ~]# 

6、准备客户端证书环境

上面服务端证书配置完成,下面是配置客户端证书

[root@openvpn 3]# cp -r /usr/share/easy-rsa/ /etc/openvpn/easy-rsa-client
[root@openvpn 3]# cp /usr/share/doc/easy-rsa/vars.example /etc/openvpn/easy-rsa-client/3/vars
[root@openvpn 3]# cd /etc/openvpn/easy-rsa-client/3/
[root@openvpn 3]# pwd
/etc/openvpn/easy-rsa-client/3
[root@openvpn 3]# ls
easyrsa  openssl-easyrsa.cnf  vars  x509-types
[root@openvpn 3]# tree
.
├── easyrsa
├── openssl-easyrsa.cnf
├── vars
└── x509-types
    ├── ca
    ├── client
    ├── code-signing
    ├── COMMON
    ├── email
    ├── kdc
    ├── server
    └── serverClient

1 directory, 11 files

#生成证书申请所需目录pki和文件
[root@openvpn 3]# ./easyrsa init-pki

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa-client/3.0.8/vars  #生成新目录

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


[root@openvpn 3]# tree
.
├── easyrsa
├── openssl-easyrsa.cnf
├── pki       #生成新目录
│   ├── openssl-easyrsa.cnf
│   ├── private
│   ├── reqs
│   └── safessl-easyrsa.cnf
├── vars
└── x509-types
    ├── ca
    ├── client
    ├── code-signing
    ├── COMMON
    ├── email
    ├── kdc
    ├── server
    └── serverClient

4 directories, 13 files
[root@openvpn 3]# 
#修改给客户端颁发的证书的有效期,比如:90天
[root@openvpn 3]# vi vars 
set_var EASYRSA_CERT_EXPIRE    90

客户端证书自动颁发脚本

[root@openvpn ~]# cat openvpn-user-crt.sh 
#!/bin/bash
. /etc/init.d/functions

OPENVPN_SERVER=39.101.161.10
PASS=123456

remove_cert () {
    rm -rf /etc/openvpn/client/${NAME} 
    find /etc/openvpn/ -name "$NAME.*" -delete
}

create_cert () {
    cd /etc/openvpn/easy-rsa-client/3
    ./easyrsa  gen-req ${NAME} nopass <<EOF

EOF

    cd /etc/openvpn/easy-rsa-server/3
    ./easyrsa import-req /etc/openvpn/easy-rsa-client/3/pki/reqs/${NAME}.req ${NAME}


    ./easyrsa sign client ${NAME} <<EOF
yes
EOF

    mkdir  /etc/openvpn/client/${NAME}
    cp /etc/openvpn/easy-rsa-server/3/pki/issued/${NAME}.crt /etc/openvpn/client/${NAME}
    cp /etc/openvpn/easy-rsa-client/3/pki/private/${NAME}.key  /etc/openvpn/client/${NAME}
    cp /etc/openvpn/certs/{ca.crt,dh.pem,ta.key} /etc/openvpn/client/${NAME}
    cat >  /etc/openvpn/client/${NAME}/client.ovpn <<EOF
client
dev tun
proto tcp
remote $OPENVPN_SERVER 1194
resolv-retry infinite
nobind
#persist-key
#persist-tun
ca ca.crt
cert $NAME.crt
key $NAME.key
remote-cert-tls server
#tls-auth ta.key 1
cipher AES-256-CBC
verb 3
compress lz4-v2
EOF

    echo "证书存放路径:/etc/openvpn/client/${NAME},证书文件如下:"
    echo -e "\\E[1;32m******************************************************************\\E[0m"
    ls -l /etc/openvpn/client/${NAME}
    echo -e "\\E[1;32m******************************************************************\\E[0m"
    cd /etc/openvpn/client/${NAME} 
    zip -qP "$PASS" /root/${NAME}.zip * 
    action  "证书的打包文件已生成: /root/${NAME}.zip"
}


read -p "请输入用户的姓名拼音(如:yzil): " NAME

remove_cert
create_cert
[root@openvpn ~]# sh openvpn-user-crt.sh 
请输入用户的姓名拼音(如:yzil): yzil

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa-client/3.0.8/vars
Using SSL: openssl OpenSSL 1.1.1g FIPS  21 Apr 2020
Generating a RSA private key
.......+++++
...............................................+++++
writing new private key to '/etc/openvpn/easy-rsa-client/3/pki/easy-rsa-27037.H4RXWn/tmp.aHGaf5'
-----
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) [yzil]:
Keypair and certificate request completed. Your files are:
req: /etc/openvpn/easy-rsa-client/3/pki/reqs/yzil.req
key: /etc/openvpn/easy-rsa-client/3/pki/private/yzil.key



Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa-server/3.0.8/vars
Using SSL: openssl OpenSSL 1.1.1g FIPS  21 Apr 2020

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



Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa-server/3.0.8/vars
Using SSL: openssl OpenSSL 1.1.1g FIPS  21 Apr 2020


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                = yzil


Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: Using configuration from /etc/openvpn/easy-rsa-server/3/pki/easy-rsa-27085.JYZzrn/tmp.P5iEZS
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'yzil'
Certificate is to be certified until Aug 14 03:36:31 2023 GMT (825 days)

Write out database with 1 new entries
Data Base Updated

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


cp: cannot stat '/etc/openvpn/certs/ca.crt': No such file or directory
cp: cannot stat '/etc/openvpn/certs/dh.pem': No such file or directory
cp: cannot stat '/etc/openvpn/certs/ta.key': No such file or directory
证书存放路径:/etc/openvpn/client/yzil,证书文件如下:
******************************************************************
total 16
-rw-r--r-- 1 root root  226 May 11 11:36 client.ovpn
-rw------- 1 root root 4486 May 11 11:36 yzil.crt
-rw------- 1 root root 1704 May 11 11:36 yzil.key
******************************************************************
证书的打包文件已生成: /root/yzil.zip                       [  OK  ]
[root@openvpn ~]# 
[root@openvpn ~]# ll /etc/openvpn/client/
total 0
drwxr-xr-x 2 root root 57 May 11 11:36 yzil
[root@openvpn ~]# sz /root/yzil.zip 

7、准备OpenVPN服务器配置文件

服务器端配置文件说明

#server.conf文件中排除掉#开头的行和空行
[root@openvpn ~]# grep -Ev "^#|^$" /etc/openvpn/server.conf 
;local a.b.c.d   #本机监听IP,默认为本机所有IP
port 1194      #端口
;proto tcp     #协议,生产推荐使用TCP
proto udp      #默认协议
;dev tap       #创建一个以太网隧道,以太网使用tap,一个tap设备允许完整的以太网帧通过openvpn隧道,可提供非ip协议的支持,比如IPX协议和AppleTalk协议,tap等同于一个以太网设备,它操作第二层数据包如以太网数据帧
dev tun       #创建一个路由IP隧道,生产推荐使用tun,互联网使用tun,一个tun设备大多时候,被用于基于IP协议的通讯。tun模拟了网络层设备,操作第三层数据包比如IP数据封包
;dev-node MyTap    #TAP-Win32适配器。非windows不需要配置
ca ca.crt          #ca证书文件
cert server.crt    #服务器证书文件
key server.key     #服务器私钥文件
dh dh2048.pem      #dh参数文件
;topology subnet    
server 10.8.0.0 255.255.255.0  #客户端连接后分配IP的地址池,服务器默认会占用第一个IP10.8.0.1将座位客户端的网关
ifconfig-pool-persist ipp.txt  #为客户端分配固定IP,不需要配置,建议注释
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100  #配置网桥模式,不需要配置,建议注释
;server-bridge
;push "route 192.168.10.0 255.255.255.0"   #给客户端生成的到达服务器后面网段的静态路由,下一跳为openvpn服务器的10.8.0.1
;push "route 192.168.20.0 255.255.255.0"   #推送路由信息到客户端,以允许客户端能够连接到服务器背后的其它私有子网
;client-config-dir ccd   #为指定的客户端添加路由,此路由通常是客户端后面的内网网段而不是服务端的,也不需要设置
;route 192.168.40.128 255.255.255.248
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
;learn-address ./script   #运行外部脚本,创建不同组的iptables规则,无需配置
;push "redirect-gateway def1 bypass-dhcp"   #启用后,客户端所有流量都将通过vpn服务器,因此生产中一般不需要配置此项
;push "dhcp-option DNS 208.67.222.222"     #推送DNS服务器,不需要配置
;push "dhcp-option DNS 208.67.220.220"    
;client-to-client     #允许不同的client直接通信,不安全,生产环境一般不需要配置
;duplicate-cn       #多个用户共同用一个证书,一般用于测试环境,生产环境都是一个用户一个证书,无需开启
keepalive 10 120    #设置服务端检测的间隔和超时时间,默认为每10秒ping一次,如果120秒没有回应则认为对方已经down
tls-auth ta.key 0   ##访止DoS等攻击的安全增强配置,可以使用以下命令来生成:openvpn --
genkey --secret ta.key #服务器和每个客户端都需要拥有该密钥的一个拷贝。第二个参数在服务器端应
该为’0’,在客户端应该为’1’
cipher AES-256-CBC     #加密算法
;compress lz4-v2       #启用Openvpn2.4.x新版压缩算法
;push "compress lz4-v2"   #推送客户端使用新版压缩算法,和下面的comp-lzo不要同时使用
;comp-lzo            #旧户端兼容的压缩配置,需要客户端配置开启压缩,openvpn2.4.X等新版可以不
用开启
;max-clients 100     #最大客户端数
;user nobody         #运行openvpn服务的用户和组
;group nobody
persist-key        #重启VPN服务时默认会重新读取key文件,开启此配置后保留使用第一次的key文 件,生产环境无需开启
persist-tun        #启用此配置后,当重启vpn服务时,一直保持tun或者tap设备是up的,否则会先
down然后再up,生产环境无需开启
status openvpn-status.log  #openVPN状态记录文件,每分钟会记录一次
;log         openvpn.log    #第一种日志记录方式,并指定日志路径,log会在openvpn启动的时候清
空日志文件,不建议使用
;log-append  openvpn.log    #第二种日志记录方式,并指定日志路径,重启openvpn后在之前的日志后
面追加新的日志,生产环境建议使用
verb 3     #设置日志级别,0-9,级别越高记录的内容越详细,0 表示静默运行,只记
录致命错误,4 表示合理的常规用法,5 和 6 可以帮助调试连接错误。9 表示极度冗余,输出非常详细的日志
信息
;mute 20     #相同类别的信息只有前20条会输出到日志文件中
explicit-exit-notify 1   #通知客户端,在服务端重启后自动重新连接,仅能用于udp模式,tcp模式
不需要配置即可实现断开重新连接,且开启此项后tcp配置后将导致openvpn服务无法启动,所以tcp时必须不
能开启此项
[root@openvpn ~]# 

修改服务器端配置文件

[root@openvpn ~]# vim /etc/openvpn/server.conf 
[root@openvpn ~]# cat /etc/openvpn/server.conf 
port 1194
proto tcp
dev tun
ca /etc/openvpn/certs/ca.crt
cert /etc/openvpn/certs/server.crt
key /etc/openvpn/certs/server.key
dh /etc/openvpn/certs/dh.pem
server 10.8.0.0 255.255.255.0
push "route 172.30.0.0 255.255.0.0"
#client-to-client
#ifconfig-pool-persist ipp.txt
keepalive 10 120
cipher AES-256-CBC
compress lz4-v2
push "compress lz4-v2"
max-clients 2048
user openvpn
group openvpn
status /var/log/openvpn/openvpn-status.log
log-append /var/log/openvpn/openvpn.log
verb 3
mute 20
[root@openvpn ~]# 


#准备日志相关文件
[root@openvpn ~]# getent passwd openvpn 
openvpn:x:989:985:OpenVPN:/etc/openvpn:/sbin/nologin
[root@openvpn ~]# mkdir /var/log/openvpn
[root@openvpn ~]# chown openvpn.openvpn /var/log/openvpn
[root@openvpn ~]# ll -d /var/log/openvpn
drwxr-xr-x 2 openvpn openvpn 6 May 11 14:06 /var/log/openvpn
[root@openvpn ~]# 

8、准备iptables规则和内核参数

#在服务器开启ip_forward转发功能
[root@openvpn ~]# echo net.ipv4.ip_forward=1 >> /etc/sysctl.conf
[root@openvpn ~]# sysctl -p
vm.swappiness = 0
kernel.sysrq = 1
net.ipv4.neigh.default.gc_stale_time = 120
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.lo.arp_announce = 2
net.ipv4.conf.all.arp_announce = 2
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 1024
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.ip_forward = 1
[root@openvpn ~]# 

添加SNAT规则
[root@openvpn ~]# echo 'iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j MASQUERADE' >> /etc/rc.d/rc.local 
[root@openvpn ~]# chmod +x /etc/rc.d/rc.local
[root@openvpn ~]# /etc/rc.d/rc.local 
[root@openvpn ~]# iptables -vnL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
[root@openvpn ~]# iptables -vnL -t nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 MASQUERADE  all  --  *      *       10.8.0.0/24          0.0.0.0/0           

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
[root@openvpn ~]# 

9、启动OpenVPN服务

#centos8缺失unit文件,自己创建或者从centos7上复制文件
[root@openvpn ~]# vi /lib/systemd/system/openvpn@.service      
[root@openvpn ~]# cat /lib/systemd/system/openvpn@.service 
[Unit]
Description=OpenVPN Robust And Highly Flexible Tunneling Application On %I
After=network.target
[Service]
Type=notify
PrivateTmp=true
ExecStart=/usr/sbin/openvpn --cd /etc/openvpn/ --config %i.conf
[Install]
WantedBy=multi-user.target


#启动openvpn服务,注意service名称和文件名不一致
[root@openvpn ~]# systemctl daemon-reload
[root@openvpn ~]# systemctl enable --now openvpn@server
Created symlink /etc/systemd/system/multi-user.target.wants/openvpn@server.service → /usr/lib/systemd/system/openvpn@.service.

10、查看服务状态

[root@openvpn ~]# systemctl status openvpn@server.service 
● openvpn@server.service - OpenVPN Robust And Highly Flexible Tunneling Application On server
   Loaded: loaded (/usr/lib/systemd/system/openvpn@.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2021-05-11 14:24:26 CST; 11s ago
 Main PID: 27755 (openvpn)
   Status: "Initialization Sequence Completed"
    Tasks: 1 (limit: 10896)
   Memory: 1.5M
   CGroup: /system.slice/system-openvpn.slice/openvpn@server.service
           └─27755 /usr/sbin/openvpn --cd /etc/openvpn/ --config server.conf

May 11 14:24:26 openvpn.yzil.xyz systemd[1]: Starting OpenVPN Robust And Highly Flexible Tunneling Application On server.>
May 11 14:24:26 openvpn.yzil.xyz systemd[1]: Started OpenVPN Robust And Highly Flexible Tunneling Application On server.


#注意端口号
[root@openvpn ~]# ss -ntlp
State      Recv-Q     Send-Q         Local Address:Port          Peer Address:Port                                        
LISTEN     0          128                  0.0.0.0:22                 0.0.0.0:*         users:(("sshd",pid=978,fd=5))     
LISTEN     0          32                   0.0.0.0:1194               0.0.0.0:*         users:(("openvpn",pid=27755,fd=9))
[root@openvpn ~]# cat /var/log/openvpn/openvpn.log
Tue May 11 14:24:26 2021 OpenVPN 2.4.11 x86_64-redhat-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Apr 21 2021
Tue May 11 14:24:26 2021 library versions: OpenSSL 1.1.1g FIPS  21 Apr 2020, LZO 2.08
Tue May 11 14:24:26 2021 Diffie-Hellman initialized with 2048 bit key
Tue May 11 14:24:26 2021 ROUTE_GATEWAY 172.30.0.125/255.255.255.128 IFACE=eth0 HWADDR=00:16:3e:09:bb:96
Tue May 11 14:24:26 2021 TUN/TAP device tun0 opened
Tue May 11 14:24:26 2021 TUN/TAP TX queue length set to 100
Tue May 11 14:24:26 2021 /sbin/ip link set dev tun0 up mtu 1500
Tue May 11 14:24:26 2021 /sbin/ip addr add dev tun0 local 10.8.0.1 peer 10.8.0.2
Tue May 11 14:24:26 2021 /sbin/ip route add 10.8.0.0/24 via 10.8.0.2
Tue May 11 14:24:26 2021 Could not determine IPv4/IPv6 protocol. Using AF_INET
Tue May 11 14:24:26 2021 Socket Buffers: R=[87380->87380] S=[16384->16384]
Tue May 11 14:24:26 2021 Listening for incoming TCP connection on [AF_INET][undef]:1194
Tue May 11 14:24:26 2021 TCPv4_SERVER link local (bound): [AF_INET][undef]:1194
Tue May 11 14:24:26 2021 TCPv4_SERVER link remote: [AF_UNSPEC]
Tue May 11 14:24:26 2021 GID set to openvpn
Tue May 11 14:24:26 2021 UID set to openvpn
Tue May 11 14:24:26 2021 MULTI: multi_init called, r=256 v=256
Tue May 11 14:24:26 2021 IFCONFIG POOL: base=10.8.0.4 size=62, ipv6=0
Tue May 11 14:24:26 2021 IFCONFIG POOL LIST
Tue May 11 14:24:26 2021 MULTI: TCP INIT maxclients=1024 maxevents=1028
Tue May 11 14:24:26 2021 Initialization Sequence Completed
[root@openvpn ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:16:3e:09:bb:96 brd ff:ff:ff:ff:ff:ff
    inet 172.30.0.1/25 brd 172.30.0.127 scope global dynamic noprefixroute eth0
       valid_lft 315341040sec preferred_lft 315341040sec
    inet6 fe80::216:3eff:fe09:bb96/64 scope link 
       valid_lft forever preferred_lft forever
3: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 100
    link/none 
    inet 10.8.0.1 peer 10.8.0.2/32 scope global tun0
       valid_lft forever preferred_lft forever
    inet6 fe80::65e7:d75a:2597:dcd1/64 scope link stable-privacy 
       valid_lft forever preferred_lft forever
[root@openvpn ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.30.0.125    0.0.0.0         UG    100    0        0 eth0
10.8.0.0        10.8.0.2        255.255.255.0   UG    0      0        0 tun0
10.8.0.2        0.0.0.0         255.255.255.255 UH    0      0        0 tun0
172.30.0.0      0.0.0.0         255.255.255.128 U     100    0        0 eth0



#验证tun网卡设备
[root@openvpn ~]# ifconfig tun0
tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1500
        inet 10.8.0.1  netmask 255.255.255.255  destination 10.8.0.2
        inet6 fe80::65e7:d75a:2597:dcd1  prefixlen 64  scopeid 0x20<link>
        unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 100  (UNSPEC)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 7  bytes 336 (336.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[root@openvpn ~]# 

11、客户端配置

客户端默认范例配置文件说明

[root@openvpn ~]# ls /usr/share/doc/openvpn/sample/sample-config-files/client.conf 
/usr/share/doc/openvpn/sample/sample-config-files/client.conf
[root@openvpn ~]# grep '^[[:alpha:]].*' /usr/share/doc/openvpn/sample/sample-config-files/client.conf
client        #声明自己是个客户端
dev tun       #接口类型,必须和服务端保持一致
proto udp     #协议类型,必须和服务端保持一致
remote my-server-1 1194   #server端的ip和端口,可以写域名但是需要可以解析成IP
resolv-retry infinite     #如果是写的server端的域名,那么就始终解析,如果域名发生变化,会重新
连接到新的域名对应的IP
nobind        #本机不绑定监听端口,客户端是随机打开端口连接到服务端的1194 
persist-key
persist-tun
ca ca.crt
cert client.crt
key client.key
remote-cert-tls server   #指定采用服务器证书校验方式
tls-auth ta.key 1
cipher AES-256-CBC
verb 3
[root@openvpn ~]# 

生成客户端用户的配置文件

#生成客户端文件,文件后缀必须为.ovpn
[root@openvpn ~]# grep '^[[:alpha:]].*' /usr/share/doc/openvpn/sample/sample-config-files/client.conf > /etc/openvpn/client/yzil/client.ovpn

#修改配置文件,内容如下
[root@openvpn ~]# vim /etc/openvpn/client/yzil/client.ovpn 
[root@openvpn ~]# cat /etc/openvpn/client/yzil/client.ovpn
client
dev tun
proto tcp
remote my-server-1 1194    #生产中为Openvpn公网ip
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client.crt
key client.key
remote-cert-tls server
tls-auth ta.key 1
cipher AES-256-CBC
verb 3                     #此值不能随意指定,否则无法通信
compress lz4-v2    #此项在OpenVPN2.4.X版本使用,需要和服务器端保持一致,如不指定,默认使用comp-lz压缩
[root@openvpn ~]# 

12、配置两台web,用于测试

[root@web01 ~]# yum install -y httpd

[root@web01 ~]# vi /var/www/html/index.html 
[root@web01 ~]# cat /var/www/html/index.html 
hello1
[root@web01 ~]# systemctl restart httpd
[root@web01 ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since Tue 2021-05-11 17:05:15 CST; 6s ago
     Docs: man:httpd.service(8)
 Main PID: 26527 (httpd)
   Status: "Started, listening on: port 80"
    Tasks: 213 (limit: 10896)
   Memory: 24.7M
   CGroup: /system.slice/httpd.service
           ├─26527 /usr/sbin/httpd -DFOREGROUND
           ├─26529 /usr/sbin/httpd -DFOREGROUND
           ├─26530 /usr/sbin/httpd -DFOREGROUND
           ├─26531 /usr/sbin/httpd -DFOREGROUND
           └─26532 /usr/sbin/httpd -DFOREGROUND

May 11 17:05:15 web01.yzil.xyz systemd[1]: httpd.service: Succeeded.
May 11 17:05:15 web01.yzil.xyz systemd[1]: Stopped The Apache HTTP Server.
May 11 17:05:15 web01.yzil.xyz systemd[1]: Starting The Apache HTTP Server...
May 11 17:05:15 web01.yzil.xyz httpd[26527]: Server configured, listening on: port 80
May 11 17:05:15 web01.yzil.xyz systemd[1]: Started The Apache HTTP Server.
[root@web01 ~]# 
[root@web02 ~]# cat /var/www/html/index.html 
hello2
[root@web02 ~]# 

13、windows客户端配置

保存证书到 openvpn 客户端默认安装目录: C:\\Program Files\\OpenVPN\\config
在服务器打包证书并下载发送给windows客户端
放置到 windows 客户端的 C:\\Program Files\\OpenVPN\\config 目录下

14、在windows客户端测试访问openvpn后端服务器

[root@cent8_yzil ~]# curl 172.30.0.10
hello1
[root@cent8_yzil ~]# curl 172.30.0.20
hello2
[root@cent8_yzil ~]# 

 

以上是关于阿里云OpenVPN部署实战的主要内容,如果未能解决你的问题,请参考以下文章

在阿里云搭建Rancher2.0和Kubernetes集群

前后端分离 -- SpringBoot + Vue实战项目 部署至阿里云服务器

Docker Kubernetes k8s 从入门到精通 阿里云实战命令

阿里云函数计算对接kafka实战

阿里云服务器安装docker并部署redis

项目部署Vue+SpringBoot前后分离个人博客项目实战部署保姆教程 Linux+docker安装部署启动一条龙教程