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