Alexu
发布于 2025-01-21 / 3 阅读
0
0

Ubuntu搭建openvpn服务器

有些内网服务无法再外网访问时可以用openvpn进行访问,本文记录一下搭建过程

1安装相关组件

openvpn, easy-rsa # 创建pki证书体系

apt install openvpn easy-rsa

ln -s /usr/share/easy-rsa ./easy-rsa # 关联easy-rsa

2 创建证书

可以增加默认配置文件vars, (可选)

#set_var EASYRSA_REQ_COUNTRY    "US"
#set_var EASYRSA_REQ_PROVINCE   "California"
#set_var EASYRSA_REQ_CITY       "San Francisco"
#set_var EASYRSA_REQ_ORG        "Copyleft Certificate Co"
#set_var EASYRSA_REQ_EMAIL      "me@example.net"
#set_var EASYRSA_REQ_OU         "My Organizational Unit"

创建证书命令

生成根证书
./easy-rsa/easyrsa init-pki  # 初始化
./easy-rsa/easyrsa build-ca nopass  # 创建根证书, nopass -- 无密码
./easy-rsa/easyrsa build-server-full server nopass # 创建server 证书
./easy-rsa/easyrsa build-client-full client nopass # 创建 client 证书
./easy-rsa/easyrsa gen-dh # 迪菲-赫尔曼

Diffie-Hellman 的作用:

在加密通信中,双方需要共享一个对称加密密钥来加密和解密消息。传统的做法是直接传输密钥,但这可能会受到中间人攻击等安全威胁。Diffie-Hellman 协议的目标是使双方能够在不直接交换密钥的情况下,安全地共同生成一个共享的密钥。

具体的工作原理:

Diffie-Hellman 协议通过数学方法允许两个通信方,在不直接传输密钥的情况下,利用公开的参数(如质数和基数)通过各自的私密值计算出相同的共享密钥。这使得即便有人窃取了公开参数和交换过程中的信息,也无法轻易推算出共享的密钥。

在 OpenVPN 中的作用:

在 OpenVPN 中,Diffie-Hellman 参数dh.pem 文件)用于生成共享密钥,使得客户端和服务器能够建立安全的加密通道。具体来说,Diffie-Hellman 用于密钥交换阶段,以确保:

  1. 客户端和服务器之间能够建立一个对称的加密密钥。

  2. 即使通信过程中的数据被窃听,窃听者也无法轻易计算出共享密钥。

完成后目录结构

ls pki/
ca.crt  certs_by_serial  dh.pem  index.txt  index.txt.attr  index.txt.attr.old  index.txt.old  inline  issued  openssl-easyrsa.cnf  private  reqs  revoked  serial  serial.old

根证书 ca.crt

迪菲-赫尔曼 dh.pem

证书和密钥分别在issue和private目录下

3服务器端配置

需要把配置文件保存到特定的目录,我这里用的是/etc/openvpn

以下是server.conf

cat server.conf 
#################################################
# Sample OpenVPN 2.6 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

# 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 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/open
# 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.
# 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" project at
# https://github.com/OpenVPN/easy-rsa
# 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).
#
# If you do not want to maintain a CA
# and have a small number of clients
# you can also use self-signed certificates
# and use the peer-fingerprint option.
# See openvpn-examples man page for a
# configuration example.
ca /etc/openvpn/ca.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/dh.pem

# Allow to connect to really old OpenVPN versions
# without AEAD support (OpenVPN 2.3.x or older)
# This adds AES-256-CBC as fallback cipher and
# keeps the modern ciphers as well.
data-ciphers AES-256-GCM:AES-128-GCM

# 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

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

# 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"
;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.
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 ta.key 0 # This file is secret

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

openvpn 启动命令:

openvpn --config /etc/openvpn/server.conf

client端的配置文件

client
dev tun
proto tcp
remote 139.196.106.97 1194
remote-random
resolv-retry infinite
ca ca.crt
cert client.crt
key client.key
nobind
verb 3
persist-key

需要把 相关文件放在同一个目录下

然后导入客户端启动即可连接

服务端配置项说明

################################################
 # 针对多客户端的OpenVPN 2.0 的服务器端配置文件示例
 #
 # 本文件用于多客户端单服务器端的OpenVPN服务器端配置
 #
 # OpenVPN也支持单机单机的配置(更多信息请查看网站上的示例页面)
 #
 # 该配置支持Windows或者Linux/BSD系统。此外,在Windows上,记得将路径加上双引号,
 # 并且使用两个反斜杠,例如:”C:\\Program Files\\OpenVPN\\config\\foo.key”
 #
 # ‘#’ or ‘;’开头的均为注释内容
 #################################################

#OpenVPN应该监听本机的哪些IP地址?
 #该命令是可选的,如果不设置,则默认监听本机的所有IP地址。
 ;local a.b.c.d

# OpenVPN应该监听哪个TCP/UDP端口?
 # 如果你想在同一台计算机上运行多个OpenVPN实例,你可以使用不同的端口号来区分它们。
 # 此外,你需要在防火墙上开放这些端口。
 port 1194

#OpenVPN使用TCP还是UDP协议?
 ;proto tcp
 proto udp

# 指定OpenVPN创建的通信隧道类型。
 # “dev tun”将会创建一个路由IP隧道,
 # “dev tap”将会创建一个以太网隧道。
 #
 # 如果你是以太网桥接模式,并且提前创建了一个名为”tap0″的与以太网接口进行桥接的虚拟接口,则你可以使用”dev tap0″
 #
 # 如果你想控制VPN的访问策略,你必须为TUN/TAP接口创建防火墙规则。
 #
 # 在非Windows系统中,你可以给出明确的单位编号(unit number),例如”tun0″。
 # 在Windows中,你也可以使用”dev-node”。
 # 在多数系统中,除非你部分禁用或者完全禁用了TUN/TAP接口的防火墙,否则VPN将不起作用。
 ;dev tap
 dev tun

# 如果你想配置多个隧道,你需要用到网络连接面板中TAP-Win32适配器的名称(例如”MyTap”)。
 # 在XP SP2或更高版本的系统中,你可能需要有选择地禁用掉针对TAP适配器的防火墙
 # 通常情况下,非Windows系统则不需要该指令。
 ;dev-node MyTap

# 设置SSL/TLS根证书(ca)、证书(cert)和私钥(key)。
 # 每个客户端和服务器端都需要它们各自的证书和私钥文件。
 # 服务器端和所有的客户端都将使用相同的CA证书文件。
 #
 # 通过easy-rsa目录下的一系列脚本可以生成所需的证书和私钥。
 # 记住,服务器端和每个客户端的证书必须使用唯一的Common Name。
 #
 # 你也可以使用遵循X509标准的任何密钥管理系统来生成证书和私钥。
 # OpenVPN 也支持使用一个PKCS #12格式的密钥文件(详情查看站点手册页面的”pkcs12″指令)
 ca ca.crt
 cert server.crt
 key server.key  # 该文件应该保密

# 指定迪菲·赫尔曼参数。
 # 你可以使用如下名称命令生成你的参数:
 #   openssl dhparam -out dh1024.pem 1024
 # 如果你使用的是2048位密钥,使用2048替换其中的1024。
 dh dh1024.pem

# 设置服务器端模式,并提供一个VPN子网,以便于从中为客户端分配IP地址。
 # 在此处的示例中,服务器端自身将占用10.8.0.1,其他的将提供客户端使用。
 # 如果你使用的是以太网桥接模式,请注释掉该行。更多信息请查看官方手册页面。
 server 10.8.0.0 255.255.255.0

# 指定用于记录客户端和虚拟IP地址的关联关系的文件。
 # 当重启OpenVPN时,再次连接的客户端将分配到与上一次分配相同的虚拟IP地址
 ifconfig-pool-persist ipp.txt

# 该指令仅针对以太网桥接模式。
 # 首先,你必须使用操作系统的桥接能力将以太网网卡接口和TAP接口进行桥接。
 # 然后,你需要手动设置桥接接口的IP地址、子网掩码;
 # 在这里,我们假设为10.8.0.4和255.255.255.0。
 # 最后,我们必须指定子网的一个IP范围(例如从10.8.0.50开始,到10.8.0.100结束),以便于分配给连接的客户端。
 # 如果你不是以太网桥接模式,直接注释掉这行指令即可。
 ;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100

# 该指令仅针对使用DHCP代理的以太网桥接模式,
 # 此时客户端将请求服务器端的DHCP服务器,从而获得分配给它的IP地址和DNS服务器地址。
 #
 # 在此之前,你也需要先将以太网网卡接口和TAP接口进行桥接。
 # 注意:该指令仅用于OpenVPN客户端,并且该客户端的TAP适配器需要绑定到一个DHCP客户端上。
 ;server-bridge

# 推送路由信息到客户端,以允许客户端能够连接到服务器背后的其他私有子网。
 # (简而言之,就是允许客户端访问VPN服务器自身所在的其他局域网)
 # 记住,这些私有子网也要将OpenVPN客户端的地址池(10.8.0.0/255.255.255.0)反馈回OpenVPN服务器。
 ;push “route 192.168.10.0 255.255.255.0”
 ;push “route 192.168.20.0 255.255.255.0”

# 为指定的客户端分配指定的IP地址,或者客户端背后也有一个私有子网想要访问VPN,
 # 那么你可以针对该客户端的配置文件使用ccd子目录。
 # (简而言之,就是允许客户端所在的局域网成员也能够访问VPN)

# 举个例子:假设有个Common Name为”Thelonious”的客户端背后也有一个小型子网想要连接到VPN,该子网为192.168.40.128/255.255.255.248。
 # 首先,你需要去掉下面两行指令的注释:
 ;client-config-dir ccd
 ;route 192.168.40.128 255.255.255.248
 # 然后创建一个文件ccd/Thelonious,该文件的内容为:
 #     iroute 192.168.40.128 255.255.255.248
 #这样客户端所在的局域网就可以访问VPN了。
 # 注意,这个指令只能在你是基于路由、而不是基于桥接的模式下才能生效。
 # 比如,你使用了”dev tun”和”server”指令。

# 再举个例子:假设你想给Thelonious分配一个固定的IP地址10.9.0.1。
 # 首先,你需要去掉下面两行指令的注释:
 ;client-config-dir ccd
 ;route 10.9.0.0 255.255.255.252
 # 然后在文件ccd/Thelonious中添加如下指令:
 #   ifconfig-push 10.9.0.1 10.9.0.2

# 如果你想要为不同群组的客户端启用不同的防火墙访问策略,你可以使用如下两种方法:
 # (1)运行多个OpenVPN守护进程,每个进程对应一个群组,并为每个进程(群组)启用适当的防火墙规则。
 # (2) (进阶)创建一个脚本来动态地修改响应于来自不同客户的防火墙规则。
 # 关于learn-address脚本的更多信息请参考官方手册页面。
 ;learn-address ./script

# 如果启用该指令,所有客户端的默认网关都将重定向到VPN,这将导致诸如web浏览器、DNS查询等所有客户端流量都经过VPN。
 # (为确保能正常工作,OpenVPN服务器所在计算机可能需要在TUN/TAP接口与以太网之间使用NAT或桥接技术进行连接)
 ;push “redirect-gateway def1 bypass-dhcp”

# 某些具体的Windows网络设置可以被推送到客户端,例如DNS或WINS服务器地址。
 # 下列地址来自opendns.com提供的Public DNS 服务器。
 ;push “dhcp-option DNS 208.67.222.222”
 ;push “dhcp-option DNS 208.67.220.220”

# 去掉该指令的注释将允许不同的客户端之间相互”可见”(允许客户端之间互相访问)。
 # 默认情况下,客户端只能”看见”服务器。为了确保客户端只能看见服务器,你还可以在服务器端的TUN/TAP接口上设置适当的防火墙规则。
 ;client-to-client

# 如果多个客户端可能使用相同的证书/私钥文件或Common Name进行连接,那么你可以取消该指令的注释。
 # 建议该指令仅用于测试目的。对于生产使用环境而言,每个客户端都应该拥有自己的证书和私钥。
 # 如果你没有为每个客户端分别生成Common Name唯一的证书/私钥,你可以取消该行的注释(但不推荐这样做)。
 ;duplicate-cn

# keepalive指令将导致类似于ping命令的消息被来回发送,以便于服务器端和客户端知道对方何时被关闭。
 # 每10秒钟ping一次,如果120秒内都没有收到对方的回复,则表示远程连接已经关闭。
 keepalive 10 120

# 出于SSL/TLS之外更多的安全考虑,创建一个”HMAC 防火墙”可以帮助抵御DoS攻击和UDP端口淹没攻击。
 # 你可以使用以下命令来生成:
 #   openvpn –genkey –secret ta.key
 #
 # 服务器和每个客户端都需要拥有该密钥的一个拷贝。
 # 第二个参数在服务器端应该为’0’,在客户端应该为’1’。
 ;tls-auth ta.key 0 # 该文件应该保密

# 选择一个密码加密算法。
 # 该配置项也必须复制到每个客户端配置文件中。
 ;cipher BF-CBC        # Blowfish (默认)
 ;cipher AES-128-CBC   # AES
 ;cipher DES-EDE3-CBC  # Triple-DES

# 在VPN连接上启用压缩。
 # 如果你在此处启用了该指令,那么也应该在每个客户端配置文件中启用它。
 comp-lzo

# 允许并发连接的客户端的最大数量
 ;max-clients 100

# 在完成初始化工作之后,降低OpenVPN守护进程的权限是个不错的主意。
 # 该指令仅限于非Windows系统中使用。
 ;user nobody
 ;group nobody

# 持久化选项可以尽量避免访问那些在重启之后由于用户权限降低而无法访问的某些资源。
 persist-key
 persist-tun

# 输出一个简短的状态文件,用于显示当前的连接状态,该文件每分钟都会清空并重写一次。
 status openvpn-status.log

# 默认情况下,日志消息将写入syslog(在Windows系统中,如果以服务方式运行,日志消息将写入OpenVPN安装目录的log文件夹中)。
 # 你可以使用log或者log-append来改变这种默认情况。
 # “log”方式在每次启动时都会清空之前的日志文件。
 # “log-append”这是在之前的日志内容后进行追加。
 # 你可以使用两种方式之一(但不要同时使用)。
 ;log         openvpn.log
 ;log-append  openvpn.log

# 为日志文件设置适当的冗余级别(0~9)。冗余级别越高,输出的信息越详细。
 #
 # 0 表示静默运行,只记录致命错误。
 # 4 表示合理的常规用法。
 # 5 和 6 可以帮助调试连接错误。
 # 9 表示极度冗余,输出非常详细的日志信息。
 verb 3

# 重复信息的沉默度。
 # 相同类别的信息只有前20条会输出到日志文件中。
 ;mute 20

使用VPN也可以用Ubuntu自带的wiregard,其他代理工具等,下次在说吧


评论