Ubuntu 1404/1604 下安装OpenVpn Server

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bingyu9875/article/details/89510930

 

Ubuntu 1404/1604 下安装OpenVpn Server

OpenVPN 是一个基于 OpenSSL 库的应用层 VPN 实现。和传统 VPN 相比,它的优点是简单易用。

OpenVPN允许参与建立VPN的单点使用共享金钥,电子证书,或者用户名/密码来进行身份验证。它大量使用了OpenSSL加密库中的SSLv3/TLSv1 协议函式库。OpenVPN能在Solaris、Linux、OpenBSD、FreeBSD、NetBSD、Mac OS X与Windows 2000/XP/Vista上运行,并包含了许多安全性的功能。它并不是一个基于Web的VPN软件,也不与IPsec及其他VPN软件包兼容。

OpenVPN2.0后引入了用户名/口令组合的身份验证方式,它可以省略客户端证书,但是仍有一份服务器证书需要被用作加密。 OpenVPN所有的通信都基于一个单一的IP端口,默认且推荐使用UDP协议通讯,同时TCP也被支持。OpenVPN连接能通过大多数的代理服务器,并且能够在NAT的环境中很好地工作。服务端具有向客户端“推送”某些网络配置信息的功能,这些信息包括:IP地址、路由设置等。OpenVPN提供了两种虚拟网络接口:通用Tun/Tap驱动,通过它们,可以建立三层IP隧道,或者虚拟二层以太网,后者可以传送任何类型的二层以太网络数据。传送的数据可通过LZO算法压缩。在选择协议时候,需要注意2个加密隧道之间的网络状况,如有高延迟或者丢包较多的情况下,请选择TCP协议作为底层协议,UDP协议由于存在无连接和重传机制,导致要隧道上层的协议进行重传,效率非常低下。

一、系统软件版本

1、系统:ubuntu 1404 / 1604

2、OpenVPN:OpenVPN 2.3.10

3、 Easy-Rsa:

3、OpenSSL:

二、安装OpenVPN

1、安装前准备

# 安装openssl和lzo,lzo用于压缩通讯数据加快传输速度
sudo apt-get install openssl libssl-dev
sudo apt-get install lzop

2、首先从apt-get安装OpenVPN及证书生成工具Easy-Rsa:

sudo apt install openvpn easy-rsa

3、修改vars文件

sudo su
cd /usr/share/easy-rsa/ 
vim vars
# 修改注册信息,比如公司地址、公司名称、部门名称等。
export KEY_COUNTRY="CN"              //你所在国家码,2个字符  
export KEY_PROVINCE="GD"             //你所在国家码,2个字符   
export KEY_CITY="ShenZhen"           //你所在城市 
export KEY_ORG="SeanTest"            //你所在组织
export KEY_EMAIL="[email protected]"  //你的邮箱地址
export KEY_OU="SeanTestUnit"         //你所在的单位
export KEY_CN=ceshi                  //随意
export KEY_NAME=ceshi                //随意
export KEY_SIZE=2048                 //生成密钥的位数
# 初始化环境变量
source vars
 
# 清除keys目录下所有与证书相关的文件
# 下面步骤生成的证书和密钥都在/usr/share/easy-rsa/keys目录里
./clean-all
 
# 生成根证书ca.crt和根密钥ca.key(一路按回车即可)
./build-ca
 
# 为服务端生成证书和私钥(一路按回车,直到提示需要输入y/n时,输入y再按回车,一共两次)
./build-key-server server
 
# 每一个登陆的VPN客户端需要有一个证书,每个证书在同一时刻只能供一个客户端连接,下面建立2份
# 为客户端生成证书和私钥(一路按回车,直到提示需要输入y/n时,输入y再按回车,一共两次)
./build-key client1
./build-key client2
 
# 创建迪菲·赫尔曼密钥,会生成dh2048.pem文件(生成过程比较慢,在此期间不要去中断它)
./build-dh
执行完成会产生dh2048.pem (如果你的KEY_SIZE =1024,这里产生的文件是dh1024.pem)
 
# 生成ta.key文件(防DDos攻击、UDP淹没等恶意攻击)
openvpn --genkey --secret keys/ta.key

# 生成证书吊销链文件防止日后有人丢失证书被非法用户接入VPN
./make-crl vpncrl.pem

说明:

制作证书的过程中,需要交互的请按照提示操作。以免生成的证书无效(本人遇到过此问题,client的证书加载失败)

 

4、创建服务器配置文件

# 在openvpn的配置目录下新建一个keys目录
mkdir /etc/openvpn/keys
 
# 将需要用到的openvpn证书和密钥复制一份到刚创建好的keys目录中
cp /usr/share/easy-rsa/keys/{ca.crt,server.{crt,key},dh2048.pem,ta.key} /etc/openvpn/keys/
 
# 复制一份服务器端配置文件模板server.conf到/etc/openvpn/
gzip -d /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz
cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf /etc/openvpn/

# 查看server.conf里的配置参数
grep '^[^#;]' /etc/openvpn/server.conf

# 编辑server.conf
vim /etc/openvpn/server.conf
port 1194
# 改成tcp,默认使用udp,如果使用HTTP Proxy,必须使用tcp协议
proto tcp
dev tun # 路由模式,桥接模式用dev tap
# 路径前面加keys,全路径为/etc/openvpn/keys/ca.crt
ca keys/ca.crt
cert keys/server.crt
key keys/server.key  # This file should be kept secret
dh keys/dh2048.pem
# 默认虚拟局域网网段,不要和实际的局域网冲突即可
server 10.8.0.0 255.255.255.0 # 路由模式,桥接模式用server-bridge 。指定虚拟局域网占用的IP地址段和子网掩码,此处配置的服务器自身占用10.0.0.1。
ifconfig-pool-persist ipp.txt
# 10.0.0.0/8是我这台VPN服务器所在的内网的网段,读者应该根据自身实际情况进行修改
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100    #设置桥接模式下的IP地址
;server-bridge    #设置服务器模式
#设置需要推送到客户端的路由表
push "route 10.0.0.0 255.0.0.0"
# 可以让客户端之间相互访问直接通过openvpn程序转发,根据需要设置
client-to-client
# 如果客户端都使用相同的证书和密钥连接VPN,一定要打开这个选项,否则每个证书只允许一个人连接VPN
duplicate-cn
;push "redirect-gateway def1 bypass-dhcp"    #设置默认客户端默认网关
;push "dhcp-option DNS 208.67.222.222"       #设置客户端DNS
#每10秒ping一次,连接超时时间设为120秒。
keepalive 10 120 
#开启TLS-auth,使用ta.key防御攻击。服务器端的第二个参数值为0,客户端的为1。
tls-auth keys/ta.key 0 # This file is secret
cipher AES-256-CBC    #指定数据对称加密算法
comp-lzo
persist-key
persist-tun
# OpenVPN的状态日志,默认为/etc/openvpn/openvpn-status.log
status openvpn-status.log
# OpenVPN的运行日志,默认为/etc/openvpn/openvpn.log 
log-append openvpn.log
# 改成verb 5可以多查看一些调试信息
verb 5

详细配置说明:

#################################################
# Sample OpenVPN 2.0 config file for #
# multi-client server. #
# #
# This file is for the server side #
# of a many-clients <-> one-server #
# OpenVPN configuration. #
# #
# OpenVPN also supports #
# single-machine <-> single-machine #
# configurations (See the Examples page #
# on the web site for more info). #
# #
# This config should work on Windows #
# or Linux/BSD systems. Remember on #
# Windows to quote pathnames and use #
# double backslashes, e.g.: #
# "C:\\Program Files\\OpenVPN\\config\\foo.key" #
# #
# Comments are preceded with '#' or ';' #
#################################################
 
# Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d    //设置服务器监听地址,默认全部
 
# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one. You will need to
# open up this port on your firewall.
port 1194     //设置服务器监听端口,默认1194
 
# TCP or UDP server?
;proto tcp    //设置连接协议,TCP/UDP二选一
proto udp
 
# "dev tun" will create a routed IP tunnel,
# "dev tap" will create an ethernet tunnel.
# Use "dev tap0" if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use "dev-node" for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap    //创建的通信隧道类型,可选tun或tap
dev tun
 
# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one. On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don't need this.
;dev-node MyTap    //Windows下TAP适配器名称,默认可不启用
 
# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key). Each client
# and the server must have their own cert and
# key file. The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys. Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca ca.crt    //指定CA证书的文件路径
cert server.crt    //指定服务器端的证书文件路径
key server.key # This file should be kept secret    //指定服务器端的私钥文件路径
 
# Diffie hellman parameters.
# Generate your own with:
# openssl dhparam -out dh2048.pem 2048
dh dh2048.pem    //指定迪菲赫尔曼参数的文件路径
 
# Network topology
# Should be subnet (addressing via IP)
# unless Windows clients v2.0.9 and lower have to
# be supported (then net30, i.e. a /30 per client)
# Defaults to net30 (not recommended)
;topology subnet
 
# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.8.0.0 255.255.255.0    //指定虚拟局域网占用的IP地址段和子网掩码,此处配置的服务器自身占用10.0.0.1。
 
# Maintain a record of client <-> virtual IP address
# associations in this file. If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist ipp.txt    //服务器自动给客户端分配IP后,客户端下次连接时,仍然采用上次的IP地址(第一次分配的IP保存在ipp.txt中,下一次分配其中保存的IP)。
 
# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface. Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0. Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients. Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100    //设置桥接模式下的IP地址
 
# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses. You must first use
# your OS's bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge    //设置服务器模式
 
# Push routes to the client to allow it
# to reach other private subnets behind
# the server. Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
;push "route 192.168.10.0 255.255.255.0"    //设置需要推送到客户端的路由表
;push "route 192.168.20.0 255.255.255.0"
;push “route remote_host 255.255.255.255 net_gateway”    //设置VPN服务器本身要通过客户端原来的网关访问(取消redirect-gateway def1 bypass-dhcp选项后这项必须开启,否则无法访问OpenVPN服务器)
 
# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory "ccd" for client-specific
# configuration files (see man page for more info).
 
# EXAMPLE: Suppose the client
# having the certificate common name "Thelonious"
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
# iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious' private subnet to
# access the VPN. This example will only work
# if you are routing, not bridging, i.e. you are
# using "dev tun" and "server" directives.
 
# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
# ifconfig-push 10.9.0.1 10.9.0.2
 
# Suppose that you want to enable different
# firewall access policies for different groups
# of clients. There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
# group, and firewall the TUN/TAP interface
# for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
# modify the firewall in response to access
# from different clients. See man
# page for more info on learn-address script.
;learn-address ./script
 
# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
;push "redirect-gateway def1 bypass-dhcp"    //设置默认客户端默认网关
 
# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses. CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
;push "dhcp-option DNS 208.67.222.222"    //设置客户端DNS
;push "dhcp-option DNS 208.67.220.220"
 
# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
;client-to-client     //设置客户端是否可以访问客户端
 
# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names. This is recommended
# only for testing purposes. For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE "COMMON NAME",
# UNCOMMENT THIS LINE OUT.
;duplicate-cn    //如果客户端都使用相同的证书和密钥连接VPN,一定要打开这个选项,否则每个证书只允许一个人连接VPN
 
# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 120    //每10秒ping一次,连接超时时间设为120秒。
 
# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
# openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
tls-auth ta.key 0 # This file is secret    //开启TLS-auth,使用ta.key防御攻击。服务器端的第二个参数值为0,客户端的为1。
 
# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
# Note that 2.4 client/server will automatically
# negotiate AES-256-GCM in TLS mode.
# See also the ncp-cipher option in the manpage
cipher AES-256-CBC    //指定数据对称加密算法
 
# Enable compression on the VPN link and push the
# option to the client (2.4+ only, for earlier
# versions see below)
;compress lz4-v2
;push "compress lz4-v2"
 
# For compression compatible with older clients use comp-lzo
# If you enable it here, you must also
# enable it in the client config file.
;comp-lzo    //开启VPN连接压缩,如果服务器端开启,客户端也必须开启
 
# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100
 
# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody    //设置运行账户及组
;group nobody
 
# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key    //持久化选项可以尽量避免访问在重启时由于用户权限降低而无法访问的某些资源。
persist-tun
 
# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log    //设置启动日志
 
# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "\Program Files\OpenVPN\log" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it. Use one
# or the other (but not both).
;log openvpn.log    //设置运行日志
;log-append openvpn.log
 
# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3    //设置日志记录级别(0-9)
 
# Silence repeating messages. At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20    //设置重复消息
 
# Notify the client that when the server restarts so it
# can automatically reconnect.
explicit-exit-notify 1    //设置断线重连功能
 
crl-verify /etc/openvpn/keys/vpncrl.pem //用于注销已删除用户的key
 
# 使用Linux系统账户登录VPN
;plugin /usr/lib64/openvpn/plugins/openvpn-plugin-auth-pam.so login # login为指定使用linux本身认证
;client-cert-not-required #取消证书认证
;username-as-common-name #使用客户提供的UserName作为Common Name
 
# 使用脚本验证用户名密码登录VPN
;script-security 3 #OpenVPN使用外部程序和脚本的策略级控制
;auth-user-pass-verify /usr/local/openvpn/etc/checkpsw.sh via-env  #设置脚本
;client-cert-not-required #取消证书认证
;username-as-common-name #使用客户提供的UserName作为Common Name

附checkpsw.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

准备用户名和密码认证文件,用户名和密码用空格隔开,同时确保openvpn启动用户可读取该文件

vim psw-file
vpnuser 123456 
chmod 775 psw-file 
chown nobody.nobody psw-file

5、配置内核和防火墙,启动服务

# 开启路由转发功能
sed -i '/net.ipv4.ip_forward/s/0/1/' /etc/sysctl.conf
sed -i '/net.ipv4.ip_forward/s/#//' /etc/sysctl.conf
sysctl -p
 
# 配置防火墙,别忘记保存
iptables -I INPUT -p tcp --dport 1194 -m comment --comment "openvpn" -j ACCEPT
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j MASQUERADE
mkdir /etc/iptables
iptables-save > /etc/iptables/iptables.conf
# 关闭ufw防火墙,改成iptables,这一步按需要设置,比较ufw在Ubuntu默认关闭的。iptables和ufw任选一个即可。
ufw disable
 
# 启动openvpn并设置为开机启动
systemctl start openvpn@server  
systemctl enable openvpn@server  
# 在systemd单元文件的后面,我们通过指定特定的配置文件名来作为一个实例变量来开启OpenVPN服务,我们的配置文件名称为/etc/openvpn/server.conf,所以我们在systemd单元文件的后面添加@server来开启OpenVPN服务

6、创建客户端配置文件client.ovpn(用于客户端软件使用)

# 复制一份client.conf模板命名为client.ovpn
cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf /etc/openvpn/client.ovpn  

# 编辑client.ovpn
vim /etc/openvpn/client.ovpn
client
dev tun # 路由模式
# 改为tcp
proto tcp
# OpenVPN服务器的外网IP和端口
remote 203.195.1.2 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
# client1的证书
cert client1.crt
# client1的密钥
key client1.key
ns-cert-type server
# 去掉前面的注释
tls-auth ta.key 1
comp-lzo
verb 5

7、配置client

安装软件,可以和服务器安装的保持一致:

# 安装openssl和lzo,lzo用于压缩通讯数据加快传输速度
sudo apt-get install openssl libssl-dev
sudo apt-get install lzop

# 安装openvpn和easy-rsa
sudo apt-get install openvpn
sudo apt-get install easy-rsa

在服务器上下载回需要的文件

sz /etc/openvpn/client.ovpn /etc/openvpn/keys/ca.crt /etc/openvpn/keys/client1.crt /etc/openvpn/keys/client1.key /etc/openvpn/keys/ta.key

将OpenVPN服务器上的client.ovpn、ca.crt、client1.crt、client1.key、ta.key上传到Linux客户端安装目录下的/etc/openvpn文件夹(使用rz命令)

[root@linux64 openvpn]# pwd
/etc/openvpn
[root@linux64 openvpn]# ls
ca.crt client1.crt client1.key client.ovpn conf ta.key

启动客户端

openvpn --daemon --cd /etc/openvpn --config client.ovpn --log-append /var/log/openvpn.log &

上面是以守护进程启动的,可以把上面脚本放在/etc/rc.local实现开机启动。或者使用以服务的形式启动,如果想清晰明了,建议放在启动脚本。

参考连接:

https://blog.csdn.net/u012843189/article/details/77422505

CentOS下安装openvpn:https://www.yeboyzq.com/linux/fuwuqipeizhi/989.html

猜你喜欢

转载自blog.csdn.net/bingyu9875/article/details/89510930
今日推荐