How to set up OpenVPN service in Ubuntu system

First, let me explain that the local environment is as follows:

Operating system: Ubuntu-18.04-LTS
Internal IP: 192.168.1.110
External IP: 14.153.76.90
OpenVPN version: 2.4.4


1. Install OpenVPN
2. Create certificate and secret key

  1. Modify and initialize environment variables
  2. Create the secret key
    3. Create the server configuration file (server.conf)
    4. Configure the kernel and firewall and start the server
    5. Create the client configuration file client.ovpn (for client software use)
    6. Create a virtual server on the router Server
    7. Start the client

1. Install OpenVPN

First install some dependencies, install openssl and lzo, lzo is used to compress communication data to speed up transmission.

sudo apt-get install openssl libssl-dev
sudo apt-get install lzop

Install OpenVPN and easy-rsa

sudo apt-get install openvpn
sudo apt-get install easy-rsa

2. Create certificate and secret key

After installing easy-rsa, we can start creating the keys required for the OpenVPN service.

  1. Modify and initialize environment variables
sudo su
cd /usr/share/easy-rsa/
vim vars

# 修改注册信息,比如公司地址、公司名称、部门名称等。
export KEY_COUNTRY="CN"
export KEY_PROVINCE="GuangDong"
export KEY_CITY="ShenZhen"
export KEY_ORG="XJXH"
export KEY_EMAIL="[email protected]"
export KEY_OU="FuckItWhatever"
export KEY_NAME="EasyRSA"

# 使环境变量生效
source ./vars

# 添加 openssl 配置文档
cp openssl-1.0.0.cnf openssl.cnf

2. Create a secret key

# 清除keys目录下所有与证书相关的文件
# 下面步骤生成的证书和密钥都在/usr/share/easy-rsa/keys目录里
./clean-all

# 生成根证书ca.crt和根密钥ca.key(一路按回车即可)
./build-ca

# 为服务端生成证书和私钥, --batch 表示保持默认设置,无须回车确认
./build-key-server --batch server

# 为客户端生成证书和私钥
./build-key --batch client

# 创建迪菲·赫尔曼密钥,会生成dh2048.pem文件(生成过程比较慢,在此期间不要去中断它)
./build-dh

# 生成ta.key文件(防DDos攻击、UDP淹没等恶意攻击)
openvpn --genkey --secret keys/ta.key

3. Create a server-side configuration file (server.conf)

First, create a new keys directory in the openvpn configuration directory.

sudo mkdir -p /etc/openvpn/keys

Then, copy the openvpn certificate and key you need to the keys directory you just created.

cp /usr/share/easy-rsa/keys/{ca.crt,server.{crt,key},dh2048.pem,ta.key} /etc/openvpn/keys/

Copy a copy of the server-side configuration file template server.conf to /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/

Edit server.conf

# 服务端口
port 1194

# 使用的传输协议
proto tcp
# 路由模式,桥接模式用dev tap
dev tun

# 证书路径
ca keys/ca.crt
cert keys/server.crt
key keys/server.key

dh keys/dh2048.pem

# 默认虚拟局域网网段,不要和实际的局域网冲突即可
server 10.8.0.0 255.255.255.0

ifconfig-pool-persist /var/log/openvpn/ipp.txt

# 192.168.1.0 是我的 OpenVPN 服务器所在在局域网的网段
# 如果你的局域网不是这个,那这里需要修改成你的网段
push "route 192.168.1.0 255.255.255.0"
# 如果客户端都使用相同的证书和密钥连接VPN,一定要打开这个选项,否则每个证书只允许一个人连接VPN
duplicate-cn

# 这里如果设置了 tls-auth 则客户端也要设置,而且要跟服务器端对应,服务端为0,客户端则为 1
# 我这里注释掉了,因为我客户端没有使用 tls-auth
;tls-auth keys/ta.key 0 # This file is secret
;key-direction 0

# clients we want to allow.
max-clients 100

persist-key
persist-tun

status /var/log/openvpn/openvpn-status.log
log         /var/log/openvpn/openvpn.log
log-append  /var/log/openvpn/openvpn.log

verb 3

# 如果上面配置了传输方式为 TCP, 则此处应该注释掉,否则会产生冲突
;explicit-exit-notify 1

# 这里配置使用用户名和密码登录的支持,可以取代使用秘钥和证书登录
auth-user-pass-verify /etc/openvpn/checkpsw.sh via-env
# 这里非常重要,如果你启用了该选项,你就只需要通过用户名和密码登录了
# 但是如果你注释了该选项,那你必须使用 用户名 + 密码 + 证书 才能登录成功,缺一不可。
;verify-client-cert none
username-as-common-name
script-security 3

If you configure login using username and password, then you need to create the login verification script vim /etc/openvpn/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="/etc/openvpn/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

Then you also need to create a password book file vim /etc/openvpn/psw-file, with one user per line, and the user name and password are separated by spaces:

user1 pass1
user2 pass2
user3 pass3

At this point, the server configuration is completed.

4. Configure the kernel and firewall, and start the server
. The first step is to enable the routing and forwarding function

sed -i '/net.ipv4.ip_forward/s/0/1/' /etc/sysctl.conf
sed -i '/net.ipv4.ip_forward/s/#//' /etc/sysctl.conf
sysctl -p

The second step is to configure iptables

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

Then we save the iptables settings, and automatically load the configuration and initialize at startup. This can be quickly achieved through iptables-persistent

sudo apt-get install iptables-persistent

save rules

sudo service netfilter-persistent save
You can see that the iptables rules have been automatically loaded when you start the next time

$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:openvpn /* openvpn */

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination 

Turn off ufw firewall

ufw disable

Step 3: Start the OpenVPN service

/etc/init.d/openvpn start
# 设置开机启动
systemctl enable openvpn@server

5. Create the client configuration file client.ovpn (for client software use)

First copy a client.conf template and name it client.ovpn

mkdir ~/openvpn-client
cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf ~/openvpn-client/client.ovpn

Then modify client.ovpn, vim /etc/openvpn/client.ovpn

client
# 这里设置跟服务端一样
dev tun
proto tcp

# OpenVPN 服务端 IP 和端口
remote 14.153.76.90 1194

resolv-retry infinite

nobind

persist-key
persist-tun

# 这里设置证书和秘钥
ca ca.crt
cert client.crt
key client.key

remote-cert-tls server

# 如果服务端使用 tls-auth, 则这里也要启用
;tls-auth ta.key 1

comp-lzo

verb 3

# 用来存放用户名和密码的文件路径,这样在连接的时候就不需要手动输入用户名密码了
auth-user-pass pass.txt

After modifying the client configuration document, you need to copy the certificate file to the ~/openvpn-client folder:

cp /ect/openvpn/keys/ca.crt ~/openvpn-client
cp /usr/share/easy-rsa/keys/client.crt ~/openvpn-client
cp /usr/share/easy-rsa/keys/client.key ~/openvpn-client

Then you need to create a new pass.txt file in the openvpn-client directory. Write the username in the first line and the password in the second line:

user1
pass1

7. Start the client.
Starting the client is very simple. You only need to copy the openvpn-client folder we created in the previous step to the client machine, and then execute the following command:

cd openvpn-client
sudo openvpn --config client.ovpn

If you see log output similar to the one below, it means you have successfully connected to the VPN and you can directly access the network where the VPN server is located.

Sat Apr 20 14:30:34 2019 /sbin/ip link set dev tun0 up mtu 1500
Sat Apr 20 14:30:34 2019 /sbin/ip addr add dev tun0 local 10.8.0.6 peer 10.8.0.5
Sat Apr 20 14:30:34 2019 /sbin/ip route add 192.168.0.0/24 via 10.8.0.5
Sat Apr 20 14:30:34 2019 /sbin/ip route add 10.8.0.1/32 via 10.8.0.5
Sat Apr 20 14:30:34 2019 Initialization Sequence Completed

Guess you like

Origin blog.csdn.net/qq_45206551/article/details/132428222