Centos7搭建openvpn服务器

1 篇文章 0 订阅
1 篇文章 0 订阅

使用VMware虚拟机搭建服务器测试环境

我目前使用的是VMware16版本,Centos使用的版本是7.5。

[root@localhost elias]# cat /etc/redhat-release 
CentOS Linux release 7.5.1804 (Core)

调整Centos时区,校准时间

  1. 修改时区 ,依次选择, 5) Asia, 9) China ,1) Beijing Time,1) Yes
[root@localhost openvpn]# tzselect
Please identify a location so that time zone rules can be set correctly.
Please select a continent or ocean.
 1) Africa
 2) Americas
 3) Antarctica
 4) Arctic Ocean
 5) Asia
 6) Atlantic Ocean
 7) Australia
 8) Europe
 9) Indian Ocean
10) Pacific Ocean
11) none - I want to specify the time zone using the Posix TZ format.
#? 5
  1. 执行命令:cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
  2. 安装NTP服务
[root@localhost openvpn]# yum install ntp -y          #安装服务
[root@localhost openvpn]# ntpdate cn.pool.ntp.org     #同步时间
22 Mar 14:52:02 ntpdate[58632]: adjust time server 139.199.215.251 offset 0.000995 sec

无关重要的

查看当前系统时间:date
设置系统时间:date -s “2020-10-28 10:15:15”
查看硬件的时间:hwclock --show
设置硬件时间: hwclock --set --date “2020-10-28 17:28:00”
设置系统时间和硬件时间同步:hwclock --hctosys
保存时间,避免重启失效:clock -w
保存时间,避免重启失效 :hwclock -w

安装openvpn

yum install -y epel-release
yum install -y openvpn easy-rsa openssl openssl-devel lzo lzo-devel pam pam-devel automake pkgconfig

上述命令执行完成后,会有一个/etc/openvpn的目录,通常我们把配置文件都放在这个目录下

1.查看openvpn版本:

[root@localhost openvpn]# openvpn --version |head -n1
OpenVPN 2.4.12 x86_64-redhat-linux-gnu [Fedora EPEL patched] [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Mar 17 2022

2.复制服务端配置文件到配置文件目录

[root@openvpn ~]# cp /usr/share/doc/openvpn-2.4.xx/sample/sample-config-files/server.conf /etc/openvpn/      ##安装版本不一样,目录xx跟随调整

服务端证书

[root@localhost openvpn]# ls /usr/share/easy-rsa/3.0.8/    #easy-rsa3的版本只有如下几个文件
easyrsa  openssl-easyrsa.cnf  x509-types   
[root@localhost openvpn]# mkdir /etc/openvpn/easy-rsa	#创建easy-rsa目录
[root@localhost openvpn]# cp -r /usr/share/easy-rsa/3.0.8/*  /etc/openvpn/easy-rsa/	#将3.0.8版本下的文件复制到/etc/openvpn/easy-rsa/下

1.CA证书制作

cd /etc/openvpn/easy-rsa
[root@localhost easy-rsa]# cp /usr/share/doc/easy-rsa-3.0.8/vars.example ./vars
[root@localhost easy-rsa]# vim vars        #修改证书的相关配置,根据需要自定义,也可以忽略不设置

set_var EASYRSA_REQ_COUNTRY     "CN"          #国家
set_var EASYRSA_REQ_PROVINCE    "Anhui"    #省
set_var EASYRSA_REQ_CITY        "Heihei"       #城市
set_var EASYRSA_REQ_ORG 		"elias Co"    #组织
set_var EASYRSA_REQ_EMAIL       "elias@example.net"     #邮箱
set_var EASYRSA_REQ_OU          "elias Unit"    #公司、组织

[root@localhost easy-rsa]# ./easyrsa init-pki          #初始化pki,生成目录文件结构,会在当前路径生成pki目录
[root@localhost easy-rsa]# ./easyrsa build-ca            #创建ca证书

Note: using Easy-RSA configuration from: ./vars            #使用vars文件里面配置的信息
Generating a 2048 bit RSA private key
 
writing new private key to '/etc/openvpn/easy-rsa/pki/private/ca.key.Lg8IKADc4Q'
Enter PEM pass phrase:                  #设置ca密码(我此处是写的abc-123)
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作为名字

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        **#ca证书存放路径**

2.服务端证书server.crt

2.1).制作证书

[root@localhost easy-rsa]# ./easyrsa gen-req server nopass   #nopass设置免证书密码,如果要设置密码可以取消此参数选项
Note: using Easy-RSA configuration from: ./vars       #使用vars文件里面配置的信息
Generating a 2048 bit RSA private key

writing new private key to '/etc/openvpn/easy-rsa/pki/private/server.key.yuG9HRsSlU'

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]:    #直接回车,默认名字为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             **#密钥key的路径**

2.2).证书签名、签约

[root@localhost easy-rsa]# ./easyrsa sign server server            #第二个server是只上面服务端证书的CN名字,我们用的默认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
Using configuration from ./openssl-1.0.cnf
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:            #输入上面ca证书生成时的密码(abc-123)
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :PRINTABLE:'server'
Certificate is to be certified until May 22 03:23:38 2028 GMT (3650 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /etc/openvpn/easy-rsa/pki/issued/server.crt          **#服务端证书路径**

2.3).生成DH证书

[root@localhost easy-rsa]# ./easyrsa gen-dh     #创建Diffie-Hellman,时间有点长
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/pki/dh.pem      **#dh证书路径**

2.3).生成ta密钥

[root@localhost easy-rsa]# cd /etc/openvpn
[root@localhost openvpn]# openvpn --genkey --secret ta.key

至此服务器端证书生成完毕

客户端证书

为了便于区别,我们把客户端使用的证书存放在新的路径 /etc/openvpn/client

2.4).创建客户端证书

[root@localhost client]# mkdir -p /etc/openvpn/client
[root@localhost client]# cd /etc/openvpn/client
[root@localhost client]# cp -r /usr/share/easy-rsa/3.0.8/\* /etc/openvpn/client       #\自行删除(影响文章格式)     
[root@localhost client]# cp /usr/share/doc/easy-rsa-3.0.8/vars.example ./vars
[root@localhost client]# ./easyrsa init-pki
[root@localhost client]# ./easyrsa gen-req client nopass   #client为证书名,可自定义,nopass同样设置免密
Generating a 2048 bit RSA private key

writing new private key to '/etc/openvpn/client/pki/private/client.key.0rbEXauafe'

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               **#key路径**

2.5).对客户端证书签名、签约

#切换到服务端easy-rsa目录下:
[root@localhost client]# cd /etc/openvpn/easy-rsa
#导入req
[root@localhost easy-rsa]# ./easyrsa import-req /etc/openvpn/client/pki/reqs/client.req client
[root@localhost easy-rsa]# ./easyrsa sign client client        #签名,第一个client是固定的参数表示客户端,第二个client指上面导入的客户端证书名
[root@localhost easy-rsa]# ./easyrsa sign 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                                    #输入'yes'
Using configuration from ./openssl-1.0.cnf
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:   #输入ca密码(abc-123)
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :PRINTABLE:'client'
Certificate is to be certified until Apr 13 14:37:17 2028 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一个目录下,便于配置

cp /etc/openvpn/easy-rsa/pki/ca.crt /etc/openvpn/
cp /etc/openvpn/easy-rsa/pki/private/server.key /etc/openvpn/
cp /etc/openvpn/easy-rsa/pki/issued/server.crt /etc/openvpn/
cp /etc/openvpn/easy-rsa/pki/dh.pem /etc/openvpn/

1.修改openvpn服务端配置文件server.conf

cat /etc/openvpn/server.conf
local 0.0.0.0
port 1194           #指定端口
proto tcp            #指定协议
dev tun             #采用路由隧道模式
ca ca.crt            #ca证书位置,相对路径,表示ca.crt和server.conf要在同一目录
cert server.crt      #服务端证书
key server.key       #服务端key
dh dh.pem             #dh密钥
server 10.8.0.0 255.255.255.0        #给客户端分配的地址池
ifconfig-pool-persist ipp.txt
push "redirect-gateway def1 bypass-dhcp"     #客户端网关使用openvpn服务器网关
push "dhcp-option DNS 8.8.8.8"               #指定dns
push "dhcp-option DNS 114.114.114.114"
keepalive 10 120              #心跳检测,10秒检测一次,2分钟内没有回应则视为断线
tls-auth ta.key 0             #服务端值为0,客户端为1
cipher AES-256-CBC
comp-lzo            #传输数据压缩
persist-key
persist-tun
status openvpn-status.log
verb 3

2.设置客户端使用的配置文件(在用户客户端使用)

[root@localhost ~]yum install -y openvpn  #linux客户端安装
cp /usr/share/doc/openvpn-2.4.xx/sample/sample-config-files/client.conf /etc/openvpn/client.ovpn
cat /etc/openvpn/client.ovpn
client
dev tun
proto tcp             #和server端一致
remote 123.xxx.xxx.xxx 1194   #指定服务端IP和端口
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
ca ca.crt          #ca证书
cert client.crt      #客户端证书
key client.key      #客户端密钥
tls-auth ta.key 1    #ta密钥
cipher AES-256-CBC
comp-lzo         #传输内容压缩
verb 3         #日志级别

3.客户端所需证书(下载保存到客户端和客户端配置文件同一目录下)

/etc/openvpn/easy-rsa/pki/issued/client.crt #在服务端证书生成目录下
/etc/openvpn/client/pki/private/client.key #上面的客户端生成目录下
/etc/openvpn/easy-rsa/pki/ca.crt #ca证书
/etc/openvpn/ta.key

关闭防火墙

[root@localhost openvpn]# iptables -F
[root@localhost openvpn]# setenforce 0

服务启动

服务端:

[root@localhost openvpn]# openvpn --daemon --config server.conf --log-append /var/log/openvpn.log

windows客户端:
https://swupdate.openvpn.org/community/releases/OpenVPN-2.6.1-I001-amd64.msi
将CA文件、客户端相关证书key、配置文件拷贝至软件config目录
右键连接即可
将客户端相关证书key和配置文件拷贝至软件config目录

Linux客户端:

openvpn --daemon --cd /etc/openvpn --config client.ovpn --log-append /var/log/openvpn.log   #放后台执行  

防火墙设置

开启内核转发

1.临时开启,(写入内存,在内存中开启)
[root@localhost openvpn]# echo "1" > /proc/sys/net/ipv4/ip_forward

2.永久开启,(写入内核)
在vi /etc/sysctl.conf 下
加入此行net.ipv4.ip_forward = 1
[root@localhost openvpn]# sysctl -p  
[root@localhost ~]# sysctl -a |grep "ip_forward"    ----查看一下
net.ipv4.ip_forward = 1

关闭防火墙

[root@localhost openvpn]# iptables -F
[root@localhost openvpn]# setenforce 0

出接口NAT

iptables -t nat -A POSTROUTING -s 10.0.0.0/8 -o ens33 -j MASQUERADE   ##开启nat

Openvpn服务器切换为账号密码连接

[root@localhost easy-rsa]# cd /etc/openvpn/
[root@localhost openvpn]# vi /etc/openvpn/server.conf  #在最后一行下面增加如下配置
auth-nocache #必须要添加auth-nocache,否则客户端会报错
script-security 3   #允许使用自定义脚本
auth-user-pass-verify /etc/openvpn/checkpsw.sh via-env  #调用外面的文件,开启密码验证脚本
username-as-common-name #用户密码登陆方式验证
client-cert-not-required #加上client-cert-not-required代表只使用用户密码方式验证登录,不加则代表需要证书和用户名密码双重验证登录
增加配置密码验证脚本
复制下面脚本
#!/bin/sh
###########################################################
# checkpsw.sh (C) 2004 Mathias Sundman <mathias@openvpn.se>
#
# 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/user_passwd.txt"
LOG_FILE="/var/log/openvpn/openvpn-login.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
为密码验证脚本checkpsw.sh添加可执行性权限,执行以下命令:
[root@localhost openvpn]# chmod +x /etc/openvpn/checkpsw.sh
配置账号密码文件

配置账号/密码文件user_passwd.txt的内容,新增账号/密码到这个文件,一行一个账号,账号密码用空格隔开:
注:密码需要使用字母加数字,特殊字符等,且不能以数字开头

[root@localhost openvpn]# vi /etc/openvpn/user_passwd.txt
elias 123456

修改账号密码文件的访问权限,第一是为了安全起见,第二是启动OpenVPN服务端的用户(默认是openvpn用户)必须对账号密码文件具有可读权限

[root@localhost openvpn]# chown openvpn.openvpn user_passwd.txt

重启openvpn服务

[root@localhost openvpn]# systemctl restart openvpn@server

客户端配置

修改客户端配置
这里以 Windows 客户端为例,编辑客户端软件 OpenVPN GUI 安装路径下的config目录里名为 *.ovpn 结尾的配置文件,修改文件内容如下:

#注释掉客户端密钥认证方式
;cert client.crt
;key client.key

新增账号/密码验证方式

auth-user-pass

测试连接

编辑完保存好配置文件,使用管理员身份打开客户端程序OpenVPN GUI ,尝试重新连接OpenVPN服务端,可以看到弹出登陆框,输入账号和密码进行验证,如下图所示:
在这里插入图片描述

客户端添加账号密码文件省去手动输入账号密码

如果客户端需要记住账号/密码,以Windows客户端 OpenVPN GUI 为例,可以在客户端安装路径下的config目录里修改 *.ovpn 配置文件的配置,添加指定账号密码文件login.conf

auth-user-pass login.conf

然后在客户端安装路径下的config目录里新增login.conf文件,文件,账号密码使用换行符分隔,内容如下:

user
a123456
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值