记录一下每次搭建openvpn的过程

shadowsocks挺好用的,平时基本够用了,但是偶尔还是需要vpn的

参考的 ucloud的教程,挺有帮助,https://docs.ucloud.cn/software/vpn/OpenVPN4Ubuntu.html

  1. 安装openvpn

    1
    2
    3
    ⋊> apt-get update
    ⋊> apt-get install openvpn libssl-dev openssl
    ⋊> apt-get install easy-rsa
  2. 配置 vars

    1
    2
    3
    4
    ⋊> cp -r /usr/share/easy-rsa/ /etc/openvpn/easy-rsa/
    ⋊> cd /etc/openvpn/easy-rsa/
    ⋊> vim vars
    ⋊> 修改export KEY_SIZE=2048
  3. 配置 server

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    ⋊> cp -r /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/
    ⋊> gzip -d server.conf.gz
    ⋊> vim server
    需要修改的大概是这样
    proto tcp
    ca easy-rsa/keys/ca.crt
    cert easy-rsa/keys/foobar.com.crt
    key easy-rsa/keys/foobar.com.key
    dh easy-rsa/keys/dh2048.pem
    push "route 192.168.20.0 255.255.255.0"
    push "redirect-gateway def1 bypass-dhcp"
    push "dhcp-option DNS 208.67.220.220"
  4. 生成证书

    1
    2
    3
    4
    5
    6
    7
    8
    9
    ⋊> cd /etc/openvpn/easy-rsa/
    ⋊> source ./vars
    ⋊> ./clean-all
    ⋊> ./build-ca
    ⋊> ./build-key-server foobar.com
    ⋊> ./build-dh
    ⋊> ./build-key client1
    ⋊> ./build-key client2
    ⋊> openvpn --genkey --secret /etc/openvpn/easy-rsa/keys/ta.key
  5. 启动服务,修改iptables

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    ⋊> sudo service openvpn start
    ⋊> vim /etc/sysctl.conf
    ⋊> 修改 net.ipv4.ip_forward 为 1
    ⋊> sysctl -p
    ⋊> iptables -t nat -A POSTROUTING -s 10.20.0.0/24 -o eth0 -j MASQUERADE
    ⋊> ptables -A INPUT -p TCP --dport 1194 -j ACCEPT
    ⋊> iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    ⋊> vim /etc/network/if-post-down.d/iptables
    填写
    #!/bin/bash
    iptables-save > /etc/iptables.rules
    ⋊> chmod +x /etc/network/if-post-down.d/iptables
    ⋊> vim /etc/network/if-pre-up.d/iptables
    填写
    #!/bin/bash
    iptables-restore < /etc/iptables.rules
    ⋊> chmod +x /etc/network/if-pre-up.d/iptables
  6. 拷贝配置到本地

    主要是这4个文件(ca.crt,client1.crt,client1.key,ta.key)

    增加客户端配置文件,大概长这样

    client
    dev tun
    proto tcp
    remote xxx.xxx.xx.xx 1194 # 你的服务器ip
    resolv-retry infinite
    nobind
    persist-key
    persist-tun
    ca ca.crt
    cert client1.crt
    key client1.key
    comp-lzo
    verb 3