openvpn 的搭建方法

1,074 阅读11分钟

服务器端(ubuntu)

安装

  1. 安装openVPN, apt-get install openvpn
  2. 进入/etc/openvpn,如没有,则检查openvpn是否安装失败

创建证书

  1. 创建openssl的配置文件,文件名为openssl.cnf, 内容如下(也可以到openvpn安装的doc文件夹里查找,具体位置为:/usr/share/doc/openvpn/examples/sample-keys),如系统不同,则自行查找:
# Heavily borrowed from EasyRSA 3, for use with OpenSSL 1.0.*#

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

[ ca ]
default_ca = CA_default # The default ca section

####################################################################
[ CA_default ]
dir = .                           # Where everything is kept
certs = $dir                      # Where the issued certs are kept
crl_dir = $dir                    # Where the issued crl are kept
database = $dir/index.txt         # database index file.
new_certs_dir = $dir              # default place for new certs.
certificate = $dir/root.crt       # The CA certificate
serial = $dir/serial.txt          # The current serial number
crl = $dir/crl.pem                # The current CRL
private_key = $dir/root.key       # The private key
RANDFILE = $dir/.rand             # private random number file

x509_extensions = basic_exts      # The extensions to add to the cert

# This allows a V2 CRL. Ancient browsers don't like it, but anything Easy-RSA
# is designed for will. In return, we get the Issuer attached to CRLs.
crl_extensions = crl_ext

default_days = 3650 # how long to certify for
default_crl_days= 30 # how long before next CRL

default_md = sha256 # use public key default MD
preserve = no # keep passed DN ordering

# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy = policy_anything

# For the 'anything' policy, which defines allowed DN fields
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = optional
name = optional
emailAddress = optional

####################################################################
# Easy-RSA request handling
# We key off $DN_MODE to determine how to format the DN
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
default_md = sha256
distinguished_name = cn_only
x509_extensions = easyrsa_ca # The extensions to add to the self signed cert

# A placeholder to handle the $EXTRA_EXTS feature:
#%EXTRA_EXTS% # Do NOT remove or change this line as $EXTRA_EXTS support requires it
####################################################################

# Easy-RSA DN (Subject) handling
# Easy-RSA DN for cn_only support:
[ cn_only ]
commonName = Common Name (eg: your user, host, or server name)
commonName_max = 64
commonName_default = changeme

# Easy-RSA DN for org support:
[ org ]
countryName = Country Name (2 letter code)
countryName_default = KG

countryName_min = 2
countryName_max = 2

stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = NA

localityName = Locality Name (eg, city)
localityName_default = BISHKEK

0.organizationName = Organization Name (eg, company)
0.organizationName_default = OpenVPN-TEST

organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default =

commonName = Common Name (eg: your user, host, or server name)
commonName_max = 64
commonName_default =

emailAddress = Email Address
emailAddress_default = me@myhost.mydomain
emailAddress_max = 64

####################################################################
[ basic_exts ]
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always

# The Easy-RSA CA extensions
[ easyrsa_ca ]

# PKIX recommendations:
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always

# This could be marked critical, but it's nice to support reading by any
# broken clients who attempt to do so.
basicConstraints = CA:true

# Limit key usage to CA tasks. If you really want to use the generated pair as
# a self-signed cert, comment this out.
keyUsage = cRLSign, keyCertSign

# CRL extensions.
[ crl_ext ]

# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
# issuerAltName=issuer:copy

authorityKeyIdentifier=keyid:always,issuer:always

# Server extensions.
[ server ]
basicConstraints       = CA:FALSE
nsCertType             = server
nsComment              = "OpenSSL Generated Server Certificate"
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid,issuer:always
extendedKeyUsage       = serverAuth
keyUsage               = digitalSignature, keyEncipherment
  1. 使用openssl.cnf文件作为配置文件生成根密钥和证书 openssl req -new -newkey rsa:4096 -days 3650 -nodes -x509 -keyout root.key -out root.crt -subj "/C=XXX/ST=XXX/L=XXX/O=XXX/emailAddress=XXX@XXX.XXX/OU=XXX" -config openssl.cnf 其中/C代表国家,/ST代表省(州),/L代表市,/O代表组织,/emailAddress代表电子邮箱地址,/OU代表组织下的部门,如执行成功,则在当前的操作目录下生成root.crt,root.key两个文件,此处的root.crt,root.key与openssl.cnf文件里的【CA_default】节里配置的同名
  2. 创建证书数据库文件touch index.txt,文件名与openssl.cnf文件里的【CA_default】节里配置的同名
  3. 创建序列号记录文件 echo 123456 > serial.txt,文件名与openssl.cnf文件里的【CA_default】节里配置的同名
  4. 创建服务器的keyopenssl req -new -nodes -config openssl.cnf -extensions server -keyout server.key -out server.csr -subj "/C=XXX/ST=XXX/L=XXX/O=XXX/emailAddress=XXX@XXX.XXX/OU=XXX/CN=XXX"其中-subj里的配置与(2)相同
  5. 创建服务器的证书文件openssl ca -batch -config openssl.cnf -extensions server -out server.crt -in server.csr
  6. 生成pem文件openssl dhparam -out dh2048.pem 2048
  7. 生成tls的认证keyopenvpn --genkey tls-auth ta.key

构建配置文件

  1. 创建openvpn的配置文件,文件名为server.conf, 内容如下(也可以到安装的doc文件夹里查找,原始的配置文件在/usr/share/doc/openvpn/examples/sample-config-files,如系统不同,则自行查找)
#################################################
# 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 192.168.1.1  #自行修改

# 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

# TCP or UDP server?
;proto tcp
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
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

# 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 /etc/openvpn/root.crt     # 文件名与路径与上述生成的路径一致,
cert /etc/openvpn/server.crt 
key /etc/openvpn/server.key  # This file should be kept secret

# Diffie hellman parameters.
# Generate your own with:
#   openssl dhparam -out dh2048.pem 2048
dh /etc/openvpn/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.5.96.0 255.255.240.0 # ip地址段自行设置

# 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 /var/log/openvpn/ipp.txt

# 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

# 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"

# 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" # 把访问的地址转到vpn服务器里

# 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

# 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

# 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 tls-auth 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 /etc/openvpn/ta.key 0 # This file is secret # 文件名与路径与上述生成的路径一致,

# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
# Note that v2.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 (v2.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

# The maximum number of concurrently connected
# clients we want to allow.
max-clients 10 # 最大客户端连接数

# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this on non-Windows
# systems after creating a dedicated user.
;user openvpn
;group openvpn

# 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 /var/log/openvpn/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         /var/log/openvpn/openvpn.log
;log-append  /var/log/openvpn/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

# 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
  1. 按照上述文件的注释进行修改,完成配置

防火墙开放端口

  1. 执行sudo ufw allow 1194/udp开放端口,如配置文件里设置是tcp或者别的端口,麻烦自行改变该命令
  2. 执行sudo iptables -t nat -A POSTROUTING -s 10.5.96.0/8 -o enp1s0 -j MASQUERADE对数据进行转发 其中-s后面的是虚拟IP地址段,与server.conf文件中设置的客户端的地址段一致
  3. 执行sudo iptables -A INPUT -i tun0 -p udp --dport 53 -j ACCEPTsudo iptables -A FORWARD -i tun0 -o enp1s0 -p udp --dport 53 -j ACCEPT让防火墙开放DNS的解析端口,其中enp1s0为对外网关

设置转发

  1. 编辑 /etc/sysctl.conf 文件,确保以下行存在且未被注释:net.ipv4.ip_forward = 1
  2. 执行sudo sysctl -p,启用转发配置

启动服务端

直接命令行启动:sudo openvpn --config /etc/openvpn/server.conf 参数是上述修改的配置文件

系统服务启动

  1. 进入 /lib/systemd/system,修改openvpn@.service文件,正常情况下,文件内容如下,修改ExecStart里的--config参数,使其文件指向上面配置的server.conf文件,并把Type改为simple:
[Unit]
Description=OpenVPN connection to %i
PartOf=openvpn.service
Before=systemd-user-sessions.service
After=network-online.target
Wants=network-online.target
Documentation=man:openvpn(8)
Documentation=https://community.openvpn.net/openvpn/wiki/Openvpn24ManPage
Documentation=https://community.openvpn.net/openvpn/wiki/HOWTO

[Service]
Type=simple
PrivateTmp=true
WorkingDirectory=/etc/openvpn
ExecStart=/usr/sbin/openvpn --daemon ovpn-%i --status /run/openvpn/%i.status 10 --cd /etc/openvpn --script-security 2 --config /etc/openvpn/server/%i.conf --writepid /run/openvpn/%i.pid
PIDFile=/run/openvpn/%i.pid
KillMode=process
CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_CHROOT CAP_DAC_OVERRIDE CAP_AUDIT_WRITE
TasksMax=10
DeviceAllow=/dev/null rw
DeviceAllow=/dev/net/tun rw
ProtectSystem=true
ProtectHome=true
RestartSec=5s
Restart=on-failure

[Install]
WantedBy=multi-user.target
  1. 保存配置文件后,更新系统配置,sudo systemctl daemon-reload
  2. 启动openvpn服务sudo systemctl start openvpn@server.service

客户端配置

openvpn 客户端下载地址 openvpn.net/client/

密钥和证书生成

  1. 生成key,openssl req -new -nodes -config openssl.cnf -keyout client.key -out client.csr -subj "/C=XXX/ST=XXX/L=XXX/O=XXX/emailAddress=XXX@XXX.XXX/OU=XXX/CN=XXX" 其中-subj里的配置(除/CN外)与服务器相同, openssl.cnf也与服务器一致,此处注意的是如果需要创建多个key,则/CN里的内容不能重复。
  2. 根据创建出来的key生成证书 openssl ca -batch -config openssl.cnf -out client.crt -in client.csr

生成客户端的配置文件

配置文件以ovpn作为后缀名,内容如下:

client
dev tun #方式与服务器一致
proto udp  #协议与服务器一致
remote 192.168.1.1 1194 # 服务器的对外IP地址和监听端口
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server

# 加密和认证设置
cipher AES-256-CBC
auth SHA1 #认证方式必须与服务器端的一致

# 日志级别
verb 3

key-direction 1 # 客户端为1,服务端为0

# 证书和密钥
<tls-auth>
#服务器的ta.key的内容
</tls-auth>

<ca>
#根证书root.crt的内容
</ca>

<cert>
#客户端client.crt证书的内容
</cert>

<key>
#客户端client.key证书的内容
</key>

一些检查方法

  1. 查看防火墙的状态sudo ufw status
  2. 检查ip接口能否创建 ifconfig 如有eth0,则启动没有问题
  3. 检查端口有没有被监听sudo lsof -i :1194