环境:

  • 系统版本 12.04
  • OpenVPN 2.2.1

服务器安装

sudo apt-get install openvpn

生成Public key Infrastructure

sudo mkdir /etc/openvpn/easy-rsa/
sudo cp -r /usr/share/doc/openvpn/examples/easy-rsa/2.0/* /etc/openvpn/easy-rsa/

编辑/etc/openvpn/easy-rsa/vars

export KEY_COUNTRY="CN"
export KEY_PROVINCE="BJ"
export KEY_CITY="Beijing"
export KEY_ORG="Folowing ltd."
export KEY_EMAIL="admin@folowing.com"
#export KEY_EMAIL=mail@host.domain
export KEY_CN=folowing.com
export KEY_NAME=folowing.com
export KEY_OU=folowing
export PKCS11_MODULE_PATH=very_secret
export PKCS11_PIN=zaqwedcxs

编辑/etc/openvpn/easy-rsa/whichopensslcnf
将所有的[[:alnum:]] 移除

生成 CA和key

cd /etc/openvpn/easy-rsa/
source vars
./clean-all
./build-ca

生成vpn服务器的cetificates

./build-key-server {SERVER_NAME}
Sign the certificate? [y/n]:y
out of 1 certificate requests certified, commit? [y/n]y

生成.pem文件

./build-dh

所有的认证和key文件都生成在keys/目录下

cd keys/
cp {SERVER_NAME}.crt {SERVER_NAME}.key ca.crt dh1024.pem /etc/openvpn/

生成客户端认证文件

cd /etc/openvpn/easy-rsa/
source vars
./build-key rocky

将一下几个文件都拷贝到客户端

/etc/openvpn/ca.crt
/etc/openvpn/easy-rsa/keys/rocky.crt
/etc/openvpn/easy-rsa/keys/rocky.key

移除没用的客户端文件

rm -rf /etc/openvpn/easy-rsa/keys/rocky.*

vpn服务器端配置

sudo cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/
sudo gzip -d /etc/openvpn/server.conf.gz

编辑/etc/openvpn/server.conf

port 1149
ca ca.crt
cert {SERVER_NAME}.crt
key {SERVER_NAME}.key
user nobody
group nogroup

启动vpn程序

sudo service openvpn start

验证vpn是否启动

ifconfig tun0
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
inet addr:10.8.0.1  P-t-P:10.8.0.2  Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1

服务器端转发

编辑/etc/sysctl.conf

net.ipv4.ip_forward=1

编辑iptables

iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -s 10.8.0.0/24 -j ACCEPT
iptables -A FORWARD -j REJECT
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

编辑/etc/openvpn/server.conf

如果不想客户端的默认gateway成为本机,注释掉下面一句
push "redirect-gateway def1"
# 添加路由
push "route 10.xxx.xxx.xxx 255.255.255.255"

客户端设置

remote {SERVER_IP} 1149
ca /Users/rocky/.ssh/ca.crt
cert /Users/rocky/.ssh/rocky.crt
key /Users/rocky/.ssh/rocky.key

参考文章

  • https://help.ubuntu.com/12.04/serverguide/openvpn.html
  • https://forums.openvpn.net/topic10528.html
  • http://aahank.com/debian-ubuntu-vpn-server/