openvpn config

最後更新: 2018-10-10



openvpn --help


最基本的 vpn (Pre-shared key)


建立 Key:


cd C:\Program Files\OpenVPN\bin

openvpn.exe --genkey --secret key.txt                 <-- "tls-auth ta.key 0" 用的 key 是以同樣的 cmd 建立

key.txt 的內容:

# 2048 bit OpenVPN static key
-----BEGIN OpenVPN Static key V1-----
-----END OpenVPN Static key V1-----


(100.1) Side_A (10.1) <--> (10.2) Side_B (100.2)

Side_B 的設定檔: 最少 setting

dev tun
secret key.txt

如果另一端是 Linux, 那就要

dos2unix your_configure.ovpn

Side_A 的設定檔:


# 放在 /etc/openvpn 內的 *.conf 會被 /etc/init.d/openvpn start 時啟動


# dev tunX | tapX | null ( X can be omitted for a dynamic device )
dev tun

#        LOCAL_IP      REMOTE_IP

# 需要用 full path, 否則會認為 key.txt 在當前目錄
secret /etc/openvpn/key.txt

##### 以下為非必要設定 #####
# tun (OSI Layer 3) / tap (OSI Layer 2)
# 當 --dev does not begin with tun or tap 時才需要 device-type
# 用了此設定可以令 tun nic 有好的名稱, 比如 r1-r2
dev-type tun

# 在 "--dev tun" mode 時用它
# tap: always uses a subnet topology
# tun: net30 / p2p ( deprecated) / subnet
# net30: allocating one /30 subnet per client
# p2p: remote endpoint of the client's tun interface always points to the local endpoint of the server's tun interface
# subnet: changes the interpretation of the arguments of --ifconfig to mean "address netmask"
topology net30

keepalive 10 60

# log setting
mute 10
verb 4
log      /var/log/openvpn/log
status   /var/log/openvpn/status

# keep pid
writepid /var/run/


openvpn --config /etc/openvpn/toB.conf

以上 cmd 相當於:

openvpn --remote \
             --dev tun --ifconfig \
             --secret /etc/openvpn/key.txt

More info:

# By default, OpenVPN runs in point-to-point  mode  ("p2p")

--mode m

Firewall 記得開 port:

UDP / 1194               <-- Openvpn default 是用 UDP Port 的


Tue Apr 17 18:20:51 2018 Initialization Sequence Completed



ifconfig  <local IP>  <remote IP>      <---tun ( point-to-point connection )

ifconfig  <local IP> <subnet mask>  <--- tap ( bridging mode )

proto    <udp> | <tcp-client> ( start connections) | <tcp-server>  (waits connections)


verb  <n>         0 ---> 11 (Hightest)

mute <n>         重覆 n 次才 log 一句


# Fast LZO compression

comp-lzo       <yes> | <no> | <adaptive> (default)

                     (may add up to 1 byte per packet for incompressible data)

                     adaptive: selectively turn compression on or off for individual clients


Bridge (Windows Client Join Linux Side Network)



C:\Program Files\OpenVPN\config\client.ovpn

port 1194

# 當是 tcp 時, 就用 proto tcp-client
proto udp

dev tap

ping 10

secret key.txt



port 1194

proto udp

# 設定 tap device 的名單而不是自動生成
dev tap0

secret key.txt

# script-security 用來設定 up / down script 行的權限
script-security 3 system

# openvpn nic up/down 時所行的 script
up   /etc/openvpn/
down /etc/openvpn/

# 斷線重啟
keepalive 10 60

# 選擇性壓縮

# Don't close and reopen TUN/TAP device or run up/down scripts across SIGUSR1 or –ping-restart restarts
# Normally if you drop root privileges in OpenVPN, 
# the daemon cannot be restarted since it will now be unable to re-read protected key files.

# Log setting
verb 5
mute 10
log /var/log/openvpn/openvpn.log
status /var/log/openvpn/status


--ping n

# 當沒有 data 傳輸時, 就會每 n 秒在 TCP/UDP control channel ping remote host 一次
# 這個 ping 只會 ping 過去, 對方並不會 echo 回來 !!
# 作用是令 stateful firewall allow package 進去

--ping-restart n

# trigger a SIGUSR1 restart after n seconds pass without reception packet
# causing the hostname used with --remote to be re-resolved (if --resolv-retry is specified)
# In server mode, always be applied to individual client instance objects

--keepalive interval timeout

相當於 ping + ping-restart

# 此設定相當於同時設定了 "--ping" 及 "--ping-restart"
#  if mode server:
#    ping 10
#    ping-restart 120
#    push "ping 10"
#    push "ping-restart 60"
#  else
#    ping 10
#    ping-restart 60
# If used on both server and client,
# the values pushed from server will override the client local values.


not re-read the keys


Keeps tun/tap devices


Windown GUI




Auto Start

Step0: 測試 CLI 先

* .ovpn files can be found in the 'C:\Program Files\OpenVPN\config' folder

"%ProgramFiles%\OpenVPN\bin\openvpn-gui.exe" --connect xxxxx.ovpn

* Windows 7 and 8, OpenVPN-GUI must be run as administrator in order for the VPN to properly function.
   (Disable the UAC / set the program to always run as administrator)


START -> RUN -> regedit.exe

去以下的 key


新增 "S" (REG_SZ)

name: OpenVPN
value: "%ProgramFiles%\OpenVPN\bin\openvpn-gui.exe" --connect home.ovpn


用 StartupCPL2.8

* For Windows Vista and Windows 7 and 8, OpenVPN-GUI must be run as administrator in order for the VPN to properly function.
(avoid these conflicts is to disable the UAC)
(always run as administrator in the properties of the application)

有用 Opts

--silent_connection          # 1=Do not show the status dialog while connecting / non-critical warnings at startup

--append_string              # 1=Append to log file. 0=Truncate logfile

--show_balloon               # 0=Never; 1=At initial connect; 2=At every (連接成功時會 show 自己拿到的 IP)

--allow_edit                    # 1=Show "Edit Config" menu (右 click 右下角的 Icon 沒有 "Edit Config")

My Example

Windows shortcut

openvpn-gui.exe --connect xxxxx.ovpn --silent_connection 1 --append_string 0 --show_balloon 0 --allow_edit 0

Show OVPN interface

C:\Program Files\OpenVPN\bin>openvpn.exe --show-adapters

Available TAP-WIN32 adapters [name, GUID]:
'openvpn' {E8C50CC2-FB3E-4E89-BF66-699BFB7083CE}


openvpn 係自己改的名

Auto connect on Logon

Run -> taskschd.msc

"Actions" -> "Create Basic Task…"

"C:\Program Files\OpenVPN\bin\openvpn-gui.exe" --connect myprofile.ovpn


 - "When I log on"

  - "Run with highest privileges"

之後人手 run 一次測試


Install window NIC driver



C:\Program Files\OpenVPN\bin\addtap.bat

# 行一次, 多一張 NIC
# 它們可以在"硬件管理員見到"TAP-Win32 Provider V9


rem Add a new TAP virtual ethernet adapter
"C:\Program Files\OpenVPN\bin\tapinstall.exe" install "C:\Program Files\OpenVPN\driver\OemWin2k.inf" tap0901

Folder 名並不重要, 重要的是 folder 內的設定檔案名 !!




RSA Key認證入門:



# 指定了 device 名 tun0. 用 tun 時會自動找不個未用的出來
dev tap


dh   keys/dh2048.pem
ca   keys/ca.crt
cert keys/VPN-Server.crt
key  keys/VPN-Server.key  

建立 dh key

openssl dhparam -out dh2048.pem 2048



dev tap


dh   keys/dh2048.pem
ca   keys/ca.crt
cert keys/VPN-Client.crt
key  keys/VPN-Client.key

建立 CA, Crt 及 Keys 的方法:

最簡單建方法: easy-rsa




--dev-node      <interface name>

--ping-timer-rem      <--- 當 remote 的 DNS Name 有值時, 那 --ping-exit 及 ping-restart 才生效(用於 listen mode)

--inactive <sec>       <--- 沒有使用 tunnel 幾耐後就 shutdown 它

--resolv-retry <sec> <-- 幾耐解釋一次 DNS Name (Default 1 天 !!)

--local  <IP>                       <-- 用那個 ip 做 connect

--remote-random                 <-- 如果有多行 remote 時, 那會 random 選一個來連

--float                                 <-- 另一端的 VPN Parter 可以轉 IP / Port (會引發 ipchange) 不會引發 restart tunnel !

--ipchange  <cmd>              <-- 當 IP 有變時, 那就 call cmd

--connect-retry <sec>          <-- Default 60s

--connect-retry-max <n>

沒有加 float 時:

Mon Nov 11 10:59:46 2013 TCP/UDP: Incoming packet rejected from [AF_INET][2], 
 expected peer address: [AF_INET] 
 (allow this incoming source address/port by removing --remote or adding --float)


限速 (limit speed)


shaper <n Bytes>                 <--- 限制 Outgoing 的 BW 在 TCP/UDP port (i.e. eth0) 上

# If you want to limit the bandwidth in both directions, use this option on both peers.

# (OpenVPN allows n to be between 100 bytes/sec and 100 Mbytes/sec.)

algorithm to implement:

after a datagram write of b bytes is queued on the TCP/UDP port,

wait a minimum of (b / n) seconds before queuing the next write.





  • route                   <network>
  • route-gateway     <IP>
  • route-delay         <sec>
  • route-up             <cmd>
  • redirect-gateway   <--- 當有本地的 in / out traffic 都經另一端


route-delay 2




openvpn script:

* up / down-pre / down       <--- tun / tap 的 up / down

* up-restart                         <--- reconnect

* route-up

* ipchange

/etc/openvpn/           <---- 權限 root / root 的 770 都可以

# create by tim
# the tap interface name is passed as first argument


ifconfig "$1" up

ovs-vsctl --if-exists del-port "$_ovsBr" "$1"
ovs-vsctl --may-exist add-port "$_ovsBr" "$1"

sleep 3

# arp proxy
echo 1 > /proc/sys/net/ipv4/conf/$_ovsBr/proxy_arp


# Last update: 20151229


#ifconfig "$1" down

ovs-vsctl --if-exists del-port "$_ovsBr" "$1"

exit 0

當 寫錯野, 那 openvpn 就會收到 SIGHUP (killall -s HUP openvpn)會起唔返 !

Fri Aug 15 10:43:39 2014 event_wait : Interrupted system call (code=4)
Fri Aug 15 10:43:39 2014 /etc/openvpn/ tap0 1500 1577   init
interface tap0 does not exist!
tap0: ERROR while getting interface flags: No such device
Fri Aug 15 10:43:39 2014 WARNING: Failed running command (--up/--down): external program exited with error status: 255
Fri Aug 15 10:43:39 2014 Exiting 

For --dev tun execute as:

cmd tun_dev tun_mtu link_mtu ifconfig_local_ip ifconfig_remote_ip [ init | restart ]

For --dev tap execute as:

cmd tap_dev tap_mtu link_mtu ifconfig_local_ip ifconfig_netmask [ init | restart ]

root@ubuntu:/etc/openvpn# brctl show

bridge name     bridge id               STP enabled     interfaces
vboxbr0         8000.1203e3a90b89       no              tap0

--script-security level [method]

0 - Strictly no calling of external programs.

1 -  (Default)  Only  call  built-in  executables such as ifconfig, ip, route, or netsh.

2 - Allow calling of built-in executables and user-defined scripts.

3 - Allow passwords to be passed to scripts via  environmental  variables

execve -- (default) Use execve() function on Unix family OSes

--up cmd

Shell command to run after successful TUN/TAP device open (pre --user UID change) <= 亦即是會用 root 來行


當 script 執行失敗, vpn 是會起唔到的 !!




log             <file>       # log-append 它與 log 有一樣功能, 並會 overwrite file 及 create file

status        <file>

Updated,Tue Nov  5 11:00:21 2013
TUN/TAP read bytes,44598
TUN/TAP write bytes,11175
TCP/UDP read bytes,15732
TCP/UDP write bytes,3144
Auth read bytes,11224
pre-compress bytes,4442
post-compress bytes,3678
pre-decompress bytes,1145
post-decompress bytes,1210


Configure File




#AUTOSTART="home office"

# Refresh interval(in seconds): /var/run/openvpn.$NAME.status


Run as







management  <IP> <port> <pw-file>
management-log-cache <n>                         <--- 在 management 保留幾多行 log




http-proxy     <server port [auth]>
http-proxy-retry  <n>
http-proxy-timeout <sec>

socks-proxy   <server port>
socks-proxy-retry  <n>






cipher      <alg>   <---  encryption of packets

查看支持什麼 ciphers:

openvpn --show-ciphers

DES-CFB 64 bit default key (fixed)
DES-CBC 64 bit default key (fixed)
RC2-CBC 128 bit default key (variable)
RC2-CFB 128 bit default key (variable)
RC2-OFB 128 bit default key (variable)


AES-256-CFB1 256 bit default key (fixed)
AES-128-CFB8 128 bit default key (fixed)
AES-192-CFB8 192 bit default key (fixed)
AES-256-CFB8 256 bit default key (fixed)
DES-CFB1 64 bit default key (fixed)
DES-CFB8 64 bit default key (fixed)
DES-EDE3-CFB1 192 bit default key (fixed)
DES-EDE3-CFB8 192 bit default key (fixed)
SEED-CBC 128 bit default key (fixed)
SEED-OFB 128 bit default key (fixed)
SEED-CFB 128 bit default key (fixed)

openvpn --show-digests

  • message digest
MD5 128 bit digest size
RSA-MD5 128 bit digest size
SHA 160 bit digest size
RSA-SHA 160 bit digest size

openvpn --show-tls

Available TLS Ciphers,
listed in order of preference:


openvpn --show-engines

RSAX engine support [rsax]
Dynamic engine loading support [dynamic]

openvpn --test-crypto --secret /etc/openvpn/key.txt

Tue Nov 19 09:46:00 2013 Entering OpenVPN crypto self-test mode.
Tue Nov 19 09:46:00 2013 TESTING ENCRYPT/DECRYPT of packet length=1
Tue Nov 19 09:46:00 2013 TESTING ENCRYPT/DECRYPT of packet length=2
Tue Nov 19 09:46:00 2013 TESTING ENCRYPT/DECRYPT of packet length=3
Tue Nov 19 09:46:00 2013 TESTING ENCRYPT/DECRYPT of packet length=1498
Tue Nov 19 09:46:00 2013 TESTING ENCRYPT/DECRYPT of packet length=1499
Tue Nov 19 09:46:00 2013 TESTING ENCRYPT/DECRYPT of packet length=1500
Tue Nov 19 09:46:00 2013 OpenVPN crypto self-test mode SUCCEEDED.



Server Mode


mode server | p2p (default)    <-- 設置用 Server mode


--server 與 --server-bridge

它們都是 shortcut 來, 它們背後都是一堆指 !!

# 由於有 tls-server, 所用不能用 keyfile 的 login

# server 與 server-bridge 是二選 1 的



mode server
push "topology [topology]"

if dev tun AND (topology == net30 OR topology == p2p):
  if !nopool:
  if client-to-client:
    push "route"
  else if topology == net30:
    push "route"

if dev tap OR (dev tun AND topology == subnet):
  if !nopool:
  push "route-gateway"


server <network> <mask>    <-- 設備 client 的 ip range (TLS mode), 亦即是說派 IP 給 Client
                                                 /30 subnet is necessary for every connection  



server-bridge gateway netmask pool-start-IP pool-end-IP





push Setting to Client


push        <options>


; Route
; push "route"
; push "route"

; Repeat this option to set secondary DNS server addresses.
push "dhcp-option DNS"
push "dhcp-option DOMAIN"

; Gateway

# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
push "redirect-gateway def1"


Client 有關的 setting


# multiple clients with the same certificate/key ( same common name )

  • duplicate-cn                   <--- 一 certificate 可以被多個 client 共用


  • connect-freq <n> sec        <--- 一個 Client 在指定時間內可以 connect 幾多次
                                                   ( 用 --proto udp 及 --tls-auth 會有較好防 DDOS 效果)


Bridge configure (server-bridge)



server-bridge gateway netmask pool-start-IP pool-end-IP

# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface.  Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume  Finally we
# must set aside an IP range in this subnet
# (start= end= to allocate
# to connecting clients.  Leave this line commented
# out unless you are ethernet bridging.
# server-bridge



Server 的 DHCP 設定


設定 Server 如何派 IP 比 Client

用了 --server--server-bridge  就不用它們 --ifconfig-pool

# --ifconfig-pool start-IP end-IP [netmask]


# Maintain a record of client <-> virtual IP address associations in this file.
# --ifconfig-pool-persist file [seconds]
# ifconfig-pool data to "file", at "seconds" intervals (default=600)
# seconds = 0, file will be treated as read-only. (它變成了 configuration file )

ifconfig-pool-persist ipp.txt


Mon May  4 13:35:05 2015 MULTI_sva: pool returned IPv4=, IPv6=1::1300:0:b67f:0


# <Common-Name>,<IP-address>


在 tun mode 時 ipp.txt 是保存 "network id" 的


Example Server Configure


local your_ip_here
port 1194
proto udp

dev tap0
up "/etc/openvpn/ vboxbr0 tap0 1500"
down "/etc/openvpn/ vboxbr0 tap0"


#certificates and encryption
ca ca.crt
cert vpn-server.crt
key vpn-server.key  # This file should be kept secret
dh dh2048.pem
tls-auth ta.key 0 # This file is secret


max-clients 10

user nobody
group nogroup

keepalive 10 120

# log
log /var/log/openvpn.log
status openvpn-status.log
verb 3




# openvpn listen https
lport 443

# x.x.x.x is the internal IP address of the web server
port-share x.x.x.x 10443




verb 5 in its configuration file (會在 log 內見到 RWrw )

WR: real interface Write / Read

 * uppercase is used for TCP/UDP packets and lowercase is used for TUN/TAP packets.


Mon Nov  4 18:07:03 2013 us=886521 Local Options hash (VER=V4): '83c3b015'
Mon Nov  4 18:07:03 2013 us=886540 Expected Remote Options hash (VER=V4): '83c3b015'
Mon Nov  4 18:07:03 2013 us=886918 UDPv4 link local (bound): [undef]
Mon Nov  4 18:07:03 2013 us=887010 UDPv4 link remote: [undef]


Nov  4 18:08:35 2013 us=283711 Peer Connection Initiated with [AF_INET]
Mon Nov  4 18:08:36 2013 us=152528 Initialization Sequence Completed

單一個 ping package log:



client ---- server
--> eth0 | tap0 -->
     R      w
<-- eth0 | tap0 <--
     W      r


建立及使用 HMAC firewall


Add an additional layer of HMAC authentication on top of the TLS control channel to protect against DoS attacks.

原理: signing every TLS control channel packet with an HMAC signature ( Protect "TLS handshake" )

# HMAC firewall
# openvpn --genkey --secret ta.key
# The server and each client must have a copy of this key.
# This file is secret
# Server: 0
# Client: 1

tls-auth ta.key 0

Client Side:


remote Server_DNS_Name 1194
resolv-retry infinite

dev tun
proto udp

ca ca.crt
cert Client1.crt
key Client1.key

# client side 永遠是 1
tls-auth ta.key 1







  • SIGHUP        <-- 相當於 service openvpn reload

1. re-read the configuration file

2. close and reopen the network connection to its peer <-- 會有 1~2 個 ping package loss

  • SIGUSR1      <-- 相當於 service openvpn reopen    

Offers more fine-grained control over which OpenVPN subsystems are reset

Like SIGHUP,  except don’t re-read configuration file

and possibly don’t close  and reopen TUN/TAP device, re-read key files, preserve local IP address/port

--ping 及 --ping-restart 是 SIGUSR1 來

 * 此不會重建 log file

  • SIGUSR2      <-- 相當於 service openvpn status

current statistics to the syslog file (/var/log/messages) if --daemon


CRL (certificate revocation list)


Server 設定:

# ln -s /usr/share/easy-rsa/2.0/keys/crl.pem /etc/openvpn/crl.pem
crl-verify crl.pem

建立 CRL:

cd /usr/share/easy-rsa/2.0
. ./vars
./revoke-full client2                 <-- cert-name

那會建立 crl.pem

CRL file will be re-read

* any time a new client connects
* an existing client renegotiates the SSL/TLS connection (by default once per hour)

flush all clients:


A common reason why certificates need to be revoked is that the user encrypts their private key with a password, then forgets the password. By revoking the original certificate, it is possible to generate a new certificate/key pair with the user's original common name.


source ./vars

./list-crl              <-- openssl crl -text -noout -in FILE.crl


Fri Jan  3 16:59:06 2014 xx.xx.xx.xx:1194 CRL CHECK FAILED: C=CN, ST=HK, L=Hong Kong, O=xxx, OU=IT, CN=xxx, is REVOKED





# log
status          /var/log/openvpn/openvpn-status.log
log-append      /var/log/openvpn/openvpn.log
verb 3
mute 10


/var/log/openvpn/openvpn.log {
    rotate 7
    create 640 openvpn openvpn

# Test

logrotate -v -f /etc/logrotate.d/openvpn



--tls-client / --tls-server


Enable TLS and assume client/server role during TLS handshake.

The purpose of negotiating the TLS control channel.


--tls-version-min version ['or-highest']

TLS version negotiation. ("1.0", "1.1",  or  "1.2")

 --tls-timeout n

Packet retransmit timeout on TLS control channel if no  acknowledgment  from remote within n seconds (default=2). 

When OpenVPN sends a control packet to its peer, it will expect to receive an acknowledgement  within  n  seconds  or 

it  will retransmit the packet, subject to a TCP-like exponential  backoff  algorithm.

This  parameter only  applies to control channel packets. 

Data channel packets (which carry encrypted tunnel  data)  are 

never acknowledged, sequenced, or retransmitted by OpenVPN

because the higher level network protocols running on top of the tunnel

such as TCP expect this role to be left to them.


Client Setting



Do not bind to local address and port.

The IP stack will allocate a dynamic port for returning packets.

Since the value of the dynamic port could not be known in advance by a peer,

this option is only suitable for peers which will be initiating connections by using the –remote option.