Сети‎ > ‎VPN‎ > ‎Параметры OpenVPN‎ > ‎


Tunnel Options (Ч2):

--ping n

Ping remote over the TCP/UDP control channel if no packets have been sent for at least n seconds (specify --ping on both peers to cause ping packets to be sent in both directions since OpenVPN ping packets are not echoed like IP ping packets). When used in one of OpenVPN's secure modes (where --secret, --tls-server, or --tls-client is specified), the ping packet will be cryptographically secure.

This option has two intended uses:

(1) Compatibility with stateful firewalls. The periodic ping will ensure that a stateful firewall rule which allows OpenVPN UDP packets to pass will not time out.

(2) To provide a basis for the remote to test the existence of its peer using the --ping-exit option.

--ping-exit n
Causes OpenVPN to exit after n seconds pass without reception of a ping or other packet from remote. This option can be combined with --inactive, --ping, and --ping-exit to create a two-tiered inactivity disconnect.

For example,

openvpn [options...] --inactive 3600 --ping 10 --ping-exit 60

when used on both peers will cause OpenVPN to exit within 60 seconds if its peer disconnects, but will exit after one hour if no actual tunnel data is exchanged.

--ping-restart n
Similar to --ping-exit, but trigger a SIGUSR1 restart after n seconds pass without reception of a ping or other packet from remote.

This option is useful in cases where the remote peer has a dynamic IP address and a low-TTL DNS name is used to track the IP address using a service such as http://dyndns.org/ + a dynamic DNS client such as ddclient.

If the peer cannot be reached, a restart will be triggered, causing the hostname used with --remote to be re-resolved (if --resolv-retry is also specified).

In server mode, --ping-restart, --inactive, or any other type of internally generated signal will always be applied to individual client instance objects, never to whole server itself. Note also in server mode that any internally generated signal which would normally cause a restart, will cause the deletion of the client instance object instead.

In client mode, the --ping-restart parameter is set to 120 seconds by default. This default will hold until the client pulls a replacement value from the server, based on the --keepalive setting in the server configuration. To disable the 120 second default, set --ping-restart 0 on the client.

See the signals section below for more information on SIGUSR1.

Note that the behaviour of SIGUSR1 can be modified by the --persist-tun, --persist-key, --persist-local-ip, and --persist-remote-ip options.

Also note that --ping-exit and --ping-restart are mutually exclusive and cannot be used together.

--keepalive n m
Вспомогательная директива предназначена для упрощения выражения  --ping и --ping-restart в конфигурации server mode.
Таймаут сервера должен быть вдвое больше чем 2-й аргумент. This ensures that a timeout is dectected on client side before the server side drops the connection.

For example, --keepalive 10 60 expands as follows:

if mode server: ping 10 ping-restart 120 push "ping 10" push "ping-restart 60" else ping 10 ping-restart 60
Run the --ping-exit / --ping-restart timer only if we have a remote address. Use this option if you are starting the daemon in listen mode (i.e. without an explicit --remote peer), and you don't want to start clocking timeouts until a remote peer connects.
Don't close and reopen TUN/TAP device or run up/down scripts across SIGUSR1 or --ping-restart restarts.

SIGUSR1 is a restart signal similar to SIGHUP, but which offers finer-grained control over reset options.

Don't re-read key files across SIGUSR1 or --ping-restart.

This option can be combined with --user nobody to allow restarts triggered by the SIGUSR1 signal. 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.

This option solves the problem by persisting keys across SIGUSR1 resets, so they don't need to be re-read.

Preserve initially resolved local IP address and port number across SIGUSR1 or --ping-restart restarts.
Preserve most recently authenticated remote IP address and port number across SIGUSR1 or --ping-restart restarts.
Disable paging by calling the POSIX mlockall function. Requires that OpenVPN be initially run as root (though OpenVPN can subsequently downgrade its UID using the --user option).

Using this option ensures that key material and tunnel data are never written to disk due to virtual memory paging operations which occur under most modern operating systems. It ensures that even if an attacker was able to crack the box running OpenVPN, he would not be able to scan the system swap file to recover previously used ephemeral keys, which are used for a period of time governed by the --reneg options (see below), then are discarded.

The downside of using --mlock is that it will reduce the amount of physical memory available to other applications.

--up cmd
Run command cmd after successful TUN/TAP device open (pre --user UID change).


The up command is useful for specifying route commands which route IP traffic destined for private subnets which exist at the other end of the VPN connection into the tunnel.

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 ]

See the "Environmental Variables" section below for additional parameters passed as environmental variables.

Note that if cmd includes arguments, all OpenVPN-generated arguments will be appended to them to build an argument list with which the executable will be called.

Typically, cmd will run a script to add routes to the tunnel.

Normally the up script is called after the TUN/TAP device is opened. In this context, the last command line parameter passed to the script will be init. If the --up-restart option is also used, the up script will be called for restarts as well. A restart is considered to be a partial reinitialization of OpenVPN where the TUN/TAP instance is preserved (the --persist-tun option will enable such preservation). A restart can be generated by a SIGUSR1 signal, a --ping-restart timeout, or a connection reset when the TCP protocol is enabled with the --proto option. If a restart occurs, and --up-restart has been specified, the up script will be called with restart as the last parameter.

The following standalone example shows how the --up script can be called in both an initialization and restart context. (NOTE: for security reasons, don't run the following example unless UDP port 9999 is blocked by your firewall. Also, the example will run indefinitely, so you should abort with control-c).

openvpn --dev tun --port 9999 --verb 4 --ping-restart 10 --up 'echo up' --down 'echo down' --persist-tun --up-restart

Note that OpenVPN also provides the --ifconfig option to automatically ifconfig the TUN device, eliminating the need to define an --up script, unless you also want to configure routes in the --up script.

If --ifconfig is also specified, OpenVPN will pass the ifconfig local and remote endpoints on the command line to the --up script so that they can be used to configure routes such as:

route add -net netmask gw $5

Delay TUN/TAP open and possible --up script execution until after TCP/UDP connection establishment with peer.

In --proto udp mode, this option normally requires the use of --ping to allow connection initiation to be sensed in the absence of tunnel data, since UDP is a "connectionless" protocol.

On Windows, this option will delay the TAP-Win32 media state transitioning to "connected" until connection establishment, i.e. the receipt of the first authenticated packet from the peer.

--down cmd
Run command cmd after TUN/TAP device close (post --user UID change and/or --chroot ). cmd consists of a path to script (or executable program), optionally followed by arguments. The path and arguments may be single- or double-quoted and/or escaped using a backslash, and should be separated by one or more spaces.

Called with the same parameters and environmental variables as the --up option above.

Note that if you reduce privileges by using --user and/or --group, your --down script will also run at reduced privilege.

Call --down cmd/script before, rather than after, TUN/TAP close.
Enable the --up and --down scripts to be called for restarts as well as initial program start. This option is described more fully above in the --up option documentation.
--setenv name value
Set a custom environmental variable name=value to pass to script.
Relax config file syntax checking so that unknown directives will trigger a warning but not a fatal error, on the assumption that a given unknown directive might be valid in future OpenVPN versions.

This option should be used with caution, as there are good security reasons for having OpenVPN fail if it detects problems in a config file. Having said that, there are valid reasons for wanting new software features to gracefully degrade when encountered by older software versions.

--setenv-safe name value
Set a custom environmental variable OPENVPN_name=value to pass to script.

This directive is designed to be pushed by the server to clients, and the prepending of "OPENVPN_" to the environmental variable is a safety precaution to prevent a LD_PRELOAD style attack from a malicious or compromised server.

--script-security level
This directive offers policy-level control over OpenVPN's usage of external programs and scripts. Lower level values are more restrictive, higher values are more permissive. Settings for level:

0 -- Strictly no calling of external programs.
2 -- Allow calling of built-in executables and user-defined scripts.
3 -- Allow passwords to be passed to scripts via environmental variables (potentially unsafe).

OpenVPN releases before v2.3 also supported a method flag which indicated how OpenVPN should call external commands and scripts. This could be either execve or system. As of OpenVPN v2.3, this flag is no longer accepted. In most *nix environments the execve() approach has been used without any issues.

To run scripts in Windows in earlier OpenVPN versions you needed to either add a full path to the script interpreter which can parse the script or use the system flag to run these scripts. As of OpenVPN v2.3 it is now a strict requirement to have full path to the script interpreter when running non-executables files. This is not needed for executable files, such as .exe, .com, .bat or .cmd files. For example, if you have a Visual Basic script, you must use this syntax now:

--up 'C:\\Windows\\System32\\wscript.exe C:\\Program\ Files\\OpenVPN\\config\\my-up-script.vbs'

Please note the single quote marks and the escaping of the backslashes (\) and the space character.

The reason the support for the system flag was removed is due to the security implications with shell expansions when executing scripts via the system() call.

Don't output a warning message if option inconsistencies are detected between peers. An example of an option inconsistency would be where one peer uses --dev tun while the other peer uses --dev tap.

Use of this option is discouraged, but is provided as a temporary fix in situations where a recent version of OpenVPN must connect to an old version.

--user user
Change the user ID of the OpenVPN process to user after initialization, dropping privileges in the process. This option is useful to protect the system in the event that some hostile party was able to gain control of an OpenVPN session. Though OpenVPN's security features make this unlikely, it is provided as a second line of defense.

By setting user to nobody or somebody similarly unprivileged, the hostile party would be limited in what damage they could cause. Of course once you take away privileges, you cannot return them to an OpenVPN session. This means, for example, that if you want to reset an OpenVPN daemon with a SIGUSR1 signal (for example in response to a DHCP reset), you should make use of one or more of the --persist options to ensure that OpenVPN doesn't need to execute any privileged operations in order to restart (such as re-reading key files or running ifconfig on the TUN device).

--group group
Similar to the --user option, this option changes the group ID of the OpenVPN process to group after initialization.
--cd dir
Change directory to dir prior to reading any files such as configuration files, key files, scripts, etc. dir should be an absolute path, with a leading "/", and without any references to the current directory such as "." or "..".

This option is useful when you are running OpenVPN in --daemon mode, and you want to consolidate all of your OpenVPN control files in one location.

--chroot dir
Chroot to dir after initialization. --chroot essentially redefines dir as being the top level directory tree (/). OpenVPN will therefore be unable to access any files outside this tree. This can be desirable from a security standpoint.

Since the chroot operation is delayed until after initialization, most OpenVPN options that reference files will operate in a pre-chroot context.

In many cases, the dir parameter can point to an empty directory, however complications can result when scripts or restarts are executed after the chroot operation.

--setcon context
Apply SELinux context after initialization. This essentially provides the ability to restrict OpenVPN's rights to only network I/O operations, thanks to SELinux. This goes further than --user and --chroot in that those two, while being great security features, unfortunately do not protect against privilege escalation by exploitation of a vulnerable system call. You can of course combine all three, but please note that since setcon requires access to /proc you will have to provide it inside the chroot directory (e.g. with mount --bind).

Since the setcon operation is delayed until after initialization, OpenVPN can be restricted to just network-related system calls, whereas by applying the context before startup (such as the OpenVPN one provided in the SELinux Reference Policies) you will have to allow many things required only during initialization.

Like with chroot, complications can result when scripts or restarts are executed after the setcon operation, which is why you should really consider using the --persist-key and --persist-tun options.

--daemon [progname]
Стать daemon после завершении функции инициализации. Этот параметр указывает, что все сообщения и ошибки будут выводиться в сислог файл (такие как /var/log/messages), за исключением выводов скриптов и ifconfig комманд, которые будут выведены в  /dev/null  если не перенаправлены в другое место. Сислог перенаправление проводится сразу же

The optional progname parameter will cause OpenVPN to report its program name to the system logger as progname. This can be useful in linking OpenVPN messages in the syslog file with specific tunnels. When unspecified, progname defaults to "openvpn".


In OpenVPN, the vast majority of errors which occur after initialization are non-fatal.

--syslog [progname]
Direct log output to system logger, but do not become a daemon. See --daemon directive above for description of progname parameter.
Output errors to stderr instead of stdout unless log output is redirected by one of the --log options.
Set the TOS field of the tunnel packet to what the payload's TOS is.
--inetd [wait|nowait] [progname]
Use this option when OpenVPN is being run from the inetd or xinetd(8) server.

The wait/nowait option must match what is specified in the inetd/xinetd config file. The nowait mode can only be used with --proto tcp-server. The default is wait. The nowait mode can be used to instantiate the OpenVPN daemon as a classic TCP server, where client connection requests are serviced on a single port number. For additional information on this kind of configuration, see the OpenVPN FAQ: http://openvpn.net/faq.html#oneport

This option precludes the use of --daemon, --local, or --remote. Note that this option causes message and error output to be handled in the same way as the --daemon option. The optional progname parameter is also handled exactly as in --daemon.

Also note that in wait mode, each OpenVPN tunnel requires a separate TCP/UDP port and a separate inetd or xinetd entry. See the OpenVPN 1.x HOWTO for an example on using OpenVPN with xinetd: http://openvpn.net/1xhowto.html

--log file
Output logging messages to file, including output to stdout/stderr which is generated by called scripts. If file already exists it will be truncated. This option takes effect immediately when it is parsed in the command line and will supercede syslog output if --daemon or --inetd is also specified. This option is persistent over the entire course of an OpenVPN instantiation and will not be reset by SIGHUP, SIGUSR1, or --ping-restart.

Note that on Windows, when OpenVPN is started as a service, logging occurs by default without the need to specify this option.

--log-append file
Append logging messages to file. If file does not exist, it will be created. This option behaves exactly like --log except that it appends to rather than truncating the log file.
Avoid writing timestamps to log messages, even when they otherwise would be prepended. In particular, this applies to log messages sent to stdout.
--writepid file
Write OpenVPN's main process ID to file.
--nice n
(Experimental) Optimize TUN/TAP/UDP I/O writes by avoiding a call to poll/epoll/select prior to the write operation. The purpose of such a call would normally be to block until the device or socket is ready to accept the write. Such blocking is unnecessary on some platforms which don't support write blocking on UDP sockets or TUN/TAP devices. In such cases, one can optimize the event loop by avoiding the poll/epoll/select call, improving CPU efficiency by 5% to 10%.

This option can only be used on non-Windows systems, when --proto udp is specified, and when --shaper is NOT specified.

Configure a multi-homed UDP server. This option can be used when OpenVPN has been configured to listen on all interfaces, and will attempt to bind client sessions to the interface on which packets are being received, so that outgoing packets will be sent out of the same interface. Note that this option is only relevant for UDP servers and currently is only implemented on Linux.


--echo [parms...]
Выводит значение parms в log. Разработан для использования отправки сообщений в приложение, контролирующее OpenVPN.
--remap-usr1 signal
Control whether internally or externally generated SIGUSR1 signals are remapped to SIGHUP (restart without persisting state) or SIGTERM (exit).

signal can be set to "SIGHUP" or "SIGTERM". By default, no remapping occurs.

--verb n
Устанвливает детализацию выходного сообшщения до уровня n (default=1). Каждый уровень показывает всю информацию относительно предыдущего уровня. Рекомендуется ставить уровень 3 для достаточной детализации и без заваливания лишней информацией.
0 -- не выводится, за сиключением фатальных ошибок.
1 to 4 -- нормальный диапазон.
5 -- выводит символы R и W на консоль для каждого пакета (чтение/запись), прописные используются для TCP/UDP пакетов, и строчные для TUN/TAP пакетов.
6 to 11 -- диапазон диагностической информации (см errlevel.h для доп. инфо по диагностич информации ).
--status file [n]
Write operational status to file every n seconds.

Status can also be written to the syslog by sending a SIGUSR2 signal.

--status-version [n]
Choose the status file format version number. Currently n can be 1, 2, or 3 and defaults to 1.
--mute n
Log at most n consecutive messages in the same category. This is useful to limit repetitive logging of similar message types.
--comp-lzo [mode]
Использовать быстрое LZO сжатие -  может добавлять до 1 байта на пакет для несжимаемых данных.
mode - "yes", "no", или  "adaptive" (по умолчанию).
В режиме server mode, это дает также возможность включать/отключать сжатие turn для индивидуальных клиентов.
Во первых, для сжатия нужно опредлить, что клиенты поддерживают параметр --comp-lzo, хотя бы --comp-lzo no. Это будет отключать сжатие по умолчанию, но разрешит в будущем directive push from the server to dynamically change the on/off/adaptive setting. Next in a --client-config-dir file, specify the compression setting for the client, for example:

comp-lzo yes push "comp-lzo yes"

The first line sets the comp-lzo setting for the server side of the link, the second sets the client side.

When used in conjunction with --comp-lzo, this option will disable OpenVPN's adaptive compression algorithm. Normally, adaptive compression is enabled with --comp-lzo.

Adaptive compression tries to optimize the case where you have compression enabled, but you are sending predominantly uncompressible (or pre-compressed) packets over the tunnel, such as an FTP or rsync transfer of a large, compressed file. With adaptive compression, OpenVPN will periodically sample the compression process to measure its efficiency. If the data being sent over the tunnel is already compressed, the compression efficiency will be very low, triggering openvpn to disable compression for a period of time until the next re-sample test.

--management IP port [pw-file]
Enable a TCP server on IP:port to handle daemon management functions. pw-file, if specified, is a password file (password on first line) or "stdin" to prompt from standard input. The password provided will set the password which TCP clients will need to provide in order to access management functions.

The management interface can also listen on a unix domain socket, for those platforms that support it. To use a unix domain socket, specify the unix socket pathname in place of IP and set port to 'unix'. While the default behaviour is to create a unix domain socket that may be connected to by any process, the --management-client-user and --management-client-group directives can be used to restrict access.

The management interface provides a special mode where the TCP management link can operate over the tunnel itself. To enable this mode, set IP = "tunnel". Tunnel mode will cause the management interface to listen for a TCP connection on the local VPN address of the TUN/TAP interface.

While the management port is designed for programmatic control of OpenVPN by other applications, it is possible to telnet to the port, using a telnet client in "raw" mode. Once connected, type "help" for a list of commands.

For detailed documentation on the management interface, see the management-notes.txt file in the management folder of the OpenVPN source distribution.


Management interface will connect as a TCP/unix domain client to IP:port specified by --management rather than listen as a TCP server or on a unix domain socket.

If the client connection fails to connect or is disconnected, a SIGTERM signal will be generated causing OpenVPN to quit.

Query management channel for private key password and --auth-user-pass username/password. Only query the management channel for inputs which ordinarily would have been queried from the console.
Query management channel for proxy server information for a specific --remote (client-only).
Allow management interface to override --remote directives (client-only). --management-external-key Allows usage for external private key file instead of --key option (client-only).
Make OpenVPN forget passwords when management session disconnects.

This directive does not affect the --http-proxy username/password. It is always cached.

Send SIGUSR1 signal to OpenVPN if management session disconnects. This is useful when you wish to disconnect an OpenVPN session on user logoff. For --management-client this option is not needed since a disconnect will always generate a SIGTERM.
--management-log-cache n
Report tunnel up/down events to management interface.
Gives management interface client the responsibility to authenticate clients after their client certificate has been verified. See management-notes.txt in OpenVPN distribution for detailed notes.
Management interface clients must specify a packet filter file for each connecting client. See management-notes.txt in OpenVPN distribution for detailed notes.
--management-client-user u
When the management interface is listening on a unix domain socket, only allow connections from user u.
--management-client-group g
When the management interface is listening on a unix domain socket, only allow connections from group g.
--plugin module-pathname [init-string]


If you are using an RPM install of OpenVPN, see /usr/share/openvpn/plugin. The documentation is in doc and the actual plugin modules are in lib.

Multiple plugin modules can be cascaded, and modules can be used in tandem with scripts. The modules will be called by OpenVPN in the order that they are declared in the config file. If both a plugin and script are configured for the same callback, the script will be called last. If the return code of the module/script controls an authentication function (such as tls-verify, auth-user-pass-verify, or client-connect), then every module and script must return success (0) in order for the connection to be authenticated.

TUN/TAP persistent tunnel config mode:
Available with linux 2.4.7+. Эти параметры  устанваливают автономынй режим роботы OpenVPN, которые могут быть использованы для использования и удаления постоянных тунелей. 
(Standalone) Create a persistent tunnel on platforms which support them such as Linux. Normally TUN/TAP tunnels exist only for the period of time that an application has them open. This option takes advantage of the TUN/TAP driver's ability to build persistent tunnels that live through multiple instantiations of OpenVPN and die only when they are deleted or the machine is rebooted.

One of the advantages of persistent tunnels is that they eliminate the need for separate --up and --down scripts to run the appropriate ifconfig(8) and route(8) commands. These commands can be placed in the the same shell script which starts or terminates an OpenVPN session.

Another advantage is that open connections through the TUN/TAP-based tunnel will not be reset if the OpenVPN peer restarts. This can be useful to provide uninterrupted connectivity through the tunnel in the event of a DHCP reset of the peer's public IP address (see the --ipchange option above).

One disadvantage of persistent tunnels is that it is harder to automatically configure their MTU value (see --link-mtu and --tun-mtu above).

On some platforms such as Windows, TAP-Win32 tunnels are persistent by default.

(Standalone) Remove a persistent tunnel.
--dev tunX | tapX
TUN/TAP device
--user user
Optional user to be owner of this tunnel.
--group group
Optional group to be owner of this tunnel.