搭建openVPN

仅从技术层面讨论,应用场景请自行设计

举例:

  1. 从外网通过VPN连接校园网内的计算机,可以访问校园网资源;
  2. 从中国网连接世界网内的计算机,可以访问不存在的网站;

服务端安装

用debian系统为例,说明在服务器端部署的步骤。

guide on digitalocean

首先是安装openvpneasy-rsa

sudo apt-get install openvpn easy-rsa  

然后,生成密钥:

make-cadir ~/openvpn-ca  
cd ~/openvpn-ca  
# edit `vars`
vim vars  

设置以下信息,方便后续密钥的验证:

export KEY_COUNTRY="CN"  
export KEY_PROVINCE="BJ"  
export KEY_CITY="Beijing"  
export KEY_ORG="Tsinghua"  
export KEY_EMAIL="******@gmail.com"  
export KEY_OU="Tom"  
export KEY_NAME="telecomVPN"  

生成服务端及用户端的密钥:

source vars  
./clean-all
./build-ca
./build-key-server telecomVPN
./build-dh
openvpn --genkey --secret keys/ta.key # may need sudo 

# user key
./build-key clientDefault

复制服务器端密钥到相应的文件夹,解压默认的配置文件:

sudo cp ca.crt ca.key <server>.crt <server>.key ta.key dh2048.pem /etc/openvpn

gunzip -c /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz | sudo tee /etc/openvpn/server.conf  

edit /etc/openvpn/server.conf:

# enable tls-auth
tls-auth ta.key 0 # This file is secret  
key-direction 0

# uncomment
cipher AES-128-CBC  
auth SHA256

# user and group
user nobody  
group nogroup

# redirect
push "redirect-gateway def1 bypass-dhcp"  
push "dhcp-option DNS 192.168.1.1"  
push "dhcp-option DNS 8.8.8.8"

# adjust port and proto
proto udp

# auth keys
cert <server>.crt  
key <server>.key  
dh dh2048.pem  

networking configure

sudo vim /etc/sysctl.conf

# enable net.ipv4.ip_forward
net.ipv4.ip_forward=1  
# enable net.ipv4.ip_forward

sudo sysctl -p  

firewall settings

raspbian:

iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE  

启动方式(systemd):

sudo systemctl start openvpn@server

# check status
sudo systemctl status openvpn@server  
ip addr show tun0

sudo systemctl enable openvpn@server  

用户配置

在服务器生成用户配置文件:

mkdir -p client-config/files  
chmod 700 ~/client-configs/files  
cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf ~/client-config/base.conf  

编辑base.conf,改变其中的默认设置:

remote server_IP_address 1194  
proto udp

cipher AES-128-CBC  
auth SHA256  
key-direction 1

# if linux client uncomment below
# script-security 2
# up /etc/openvpn/update-resolv-conf
# down /etc/openvpn/update-resolv-conf

create new file ~/client-config/make_config.sh

#!/bin/bash

# First argument: Client identifier

KEY_DIR=~/openvpn-ca/keys  
OUTPUT_DIR=~/client-configs/files  
BASE_CONFIG=~/client-configs/base.conf

cat ${BASE_CONFIG} \  
    <(echo -e '<ca>') \
    ${KEY_DIR}/ca.crt \
    <(echo -e '</ca>\n<cert>') \
    ${KEY_DIR}/${1}.crt \
    <(echo -e '</cert>\n<key>') \
    ${KEY_DIR}/${1}.key \
    <(echo -e '</key>\n<tls-auth>') \
    ${KEY_DIR}/ta.key \
    <(echo -e '</tls-auth>') \

change mod: chmod 700 ~/client-config/make_config.sh

./make_config.sh clientDefault
# ta.key permission issue

使用方法

将上述方法生成的:clientDefault.ovpn拷贝到用户设备。然后参考不同系统的openVPN使用说明。