假设我们有两台Linux虚拟机A和B,使用A和B互相充当Server和Client

TLS模式

假设我们使用A来充当server,B来充当client

TLS Server

  • 在A中下载OpenVPN

    sudo apt-get install openvpn
    
  • /usr/share/doc/openvpn/examples/sample-keys/文件夹下有好多keys,在server中,复制ca.crtserver.keyserver.crtdh2048.pem/etc/openvpn/tls-server

    sudo cp /usr/share/doc/openvpn/examples/sample-keys/{ca.crt,server.key,server.crt,dh2048.pem} /etc/openvpn/tls-server
    
  • 编写服务器配置文件

    port 1194
    proto udp
    dev tun0
    ca ca.crt
    cert server.crt
    key server.key
    dh dh2048.pem
    server 10.8.0.0 255.255.255.0
    keepalive 10 120
    user nobody
    group nogroup
    persist-key
    persist-tun
    verb 3
    
  • 如果使用TCP连接,则修改为

    port 1194
    proto tcp-server
    dev tun0
    ca ca.crt
    cert server.crt
    key server.key
    dh dh2048.pem
    server 10.8.0.0 255.255.255.0
    keepalive 10 120
    user nobody
    group nogroup
    persist-key
    persist-tun
    verb 3
    
  • 启动OpenVPN Server

    cd /etc/openvpn/tls-server
    sudo openvpn --config server.conf
    
  • 这时如果查看IP地址可以看到tun0接口,地址是10.8.0.1

TLS Client

  • 在B中下载OpenVPN

    sudo apt-get install openvpn
    
  • 在A中/usr/share/doc/openvpn/examples/sample-keys/下找到ca.crtclient.keyclient.crt,复制到B中

    # In B
    sudo scp [A_usrname]@[A_addr]:/usr/share/doc/openvpn/examples/sample-keys/{ca.crt,client.crt,client.key} /etc/openvpn/tls-client
    
  • 编写server.conf

    client
    dev tun0
    remote [A_addr] 1194 udp
    ca ca.crt
    cert client.crt
    key client.key
    user nobody
    group nogroup
    persist-key
    persist-tun
    verb 3
    
  • 如果是TCP连接则

    client
    dev tun0
    remote [A_addr] 1194 tcp-client
    ca ca.crt
    cert client.crt
    key client.key
    user nobody
    group nogroup
    persist-key
    persist-tun
    verb 3
    
  • 运行OpenVPN Client

    cd /etc/openvpn/tls-client
    sudo openvpn --config client.conf
    
  • 这时如果执行

    ping 10.8.0.1
    

    成功,说明OpenVPN成功建立

PSK模式

PSK模式不需要配置复杂的keys,比较简单,但是安全性也会随之降低,这里我们同样让A充当Server,B充当Client

PSK Server

  • 在A中生成psk.key,并且复制一份给B

    # In A
    cd /etc/openvpn/psk-server
    openvpn --genkey --secret psk.key
    
    # In B
    cd /etc/openvpn/psk-client
    scp [A_usrname]@[A_addr]:/etc/openvpn/psk-server/psk.key .
    
  • 编写server.conf

    dev-type tun
    dev tun0
    ifconfig 10.8.0.6 10.8.0.1
    keepalive 10 120
    persist-tun
    secret psk.key
    verb 0
    # proto tcp-server
    

    如果是TCP连接,则取消注释最后一行

  • 启动OpenVPN

    cd /etc/openvpn/psk-server
    sudo openvpn --config server.conf
    

PSK Client

  • 编写client.conf

    dev-type tun
    dev tun0
    remote [A_addr] 1194 udp
    ifconfig 10.8.0.1 10.8.0.6
    keepalive 10 120
    persist-tun
    secret psk.key
    verb 0
    
  • 如果是TCP连接

    dev-type tun
    dev tun0
    remote 10.10.200.120 1194 tcp-client
    ifconfig 10.8.0.1 10.8.0.6
    keepalive 10 120
    persist-tun
    secret psk.key
    verb 0